Python Programming LanguageAs I mentioned in last night’s post, I have a friend that has asked for help with understanding how web servers work. To help him out, I’ve agreed to create a basic HTTP server to get him started. To do that, I’ve decided to create web servers in Python, Java, and C# and I’ve also decided to share the source code for those servers here with you. Since I went into a lot of discussion about the different types of HTTP servers last night, tonight I’m just going to jump straight into creating a web server using the Python programming language. So, here we go.

Just like in our C# HTTP server, our Python HTTP server will need a way to bind to a port & IP address, listen for requests, and submit responses back to the client. To do that in Python, we can use the BaseHTTPServer which is already built into Python. So, we will begin by importing the necessary references using our favorite “import” statement. After we have our modules referenced, we will need to build a simple class that will house our HEAD and GET methods. Just like before, we will need to construct our header and body. For that, we will define 2 methods, one for _writeheaders and 1 for do_GET. After that, all we have left to do is construct our server and tell it to run forever. So, without any further adieu, here is the code to build your very own Python HTTP server.

#!/usr/bin/env python

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

class BaseHandler(BaseHTTPRequestHandler):
    def _writeheaders(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_HEAD(self):
        self._writeheaders()

    def do_GET(self):
        self._writeheaders()
        self.wfile.write("""<HTML><HEAD><TITLE>Simple Server</TITLE></HEAD>
        <BODY>It worked!!!!</BODY></HTML>""")
        
serveraddr = ('', 8080)
srvr = HTTPServer(serveraddr, BaseHandler)
srvr.serve_forever()

For more information on building servers with Python, you should checkout the following books from Amazon.com:

Foundations of Python Network Programming

Python Web Programming

Related Posts

Tagged with:  

Leave a Reply