Profile

Click to view full profile
Hi, I'm Veerapat Sriarunrungrueang, an expert in technology field, especially full stack web development and performance testing.This is my coding diary. I usually develop and keep code snippets or some tricks, and update to this diary when I have time. Nowadays, I've been giving counsel to many well-known firms in Thailand.
view more...

Wednesday, November 28, 2012

Simple HTTP Server with Python

To create HTTP server in Python, we need to bind to a port & IP address, listen to that port for responding requests. To do that, we can use built-in module named BaseHTTPServer to handle HTTP requests. The main methods are do_GET and do_HEAD, we will need them to construct our header and body.

Here is a server code:
import SimpleHTTPServer
import SimpleHTTPServer
import SocketServer

# Server port
PORT = 8000

class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

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

 def do_GET(self):
  # Handle GET request
  self._writeheaders()
  self.wfile.write("""
  <html><head><title>Simple Server with Python</title></head>
   <body>
    Hello World!!!!
   </body>
  </html>""")

Handler = ServerHandler

# Initialize server object
httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()
For handling POST request, just create do_POST method in ServerHandler class. I will explain more in the next post. For this post, just want to ground the basic HTTP server knowledge.

References:

No comments:

Post a Comment