2009
Simple Webserver in Python

This snippet illustrates how one can easily build a HTTP Web Server in python. self.args will contain the query parameters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | #!/usr/bin/env python # -*- coding: utf-8 -*- # Simple WebServer Illustration # Pravin Paratey (April 15, 2009) [pravinp at gmail dot com] from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class MyHandler(BaseHTTPRequestHandler): binaryExtensions = ['.gif', '.png', '.jpg'] contentTypes = { '.css': 'text/css', '.gif': 'image/gif', '.jpg': 'image/jpg', '.png': 'image/png', 'html': 'text/html', } def do_GET(self): """ Implementing the GET method """ try: if self.path == '/': self.path = '/index.html' mode = 'r' if self.path[-4:] in self.binaryExtensions: mode = 'rb' fp = open(self.path[1:], mode) data = fp.read() fp.close() # Send response self.send_response(200) self.send_header('Content-Type', self.__getContentType()) self.send_header('Transfer-Encoding', 'chunked') self.end_headers() self.wfile.write(data) except IOError: self.send_error(404, "File not found: %s" % self.path) def __getContentType(self): """ Function to figure out content types """ content_type = 'text/plain' extension = self.path[-4:] if extension in self.contentTypes: content_type = self.contentTypes[extension] return content_type if __name__ == '__main__': server = HTTPServer(('', 8000), MyHandler) server.serve_forever() |



Adam Tauno Williams
This isn’t correct. BaseHTTPRequestHandler defaults to HTTP/1.0 which doesn’t do chunked encoding (RFC2616), and even though Transfer-Encoding: chunked is specified – this script doesn’t do chunked encoding. It serves just a simple HTTP/1.0 non-pipelined GET and disconnect.