Skip to content

Instantly share code, notes, and snippets.

@tangzero
Created February 28, 2012 18:33
Show Gist options
  • Save tangzero/1934187 to your computer and use it in GitHub Desktop.
Save tangzero/1934187 to your computer and use it in GitHub Desktop.
Basic HTTP Server in Python
#!/usr/bin/env python
import SocketServer
from os.path import getsize
from mimetypes import read_mime_types
from datetime import date
# Mon, 27 Jul 2009 12:28:53 GMT
template = """HTTP/1.1 200 OK
Date: %s
Server: GonowServer
Content-Length: %d
Content-Type: %s
%s
"""
class HTTPHandler(SocketServer.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
verb, resource = self.data.split()[0:2]
with open("site" + resource) as f:
response = template % (
date.today().isocalendar(),
getsize(f.name),
read_mime_types(f.name),
f.read()
)
self.request.sendall(response)
if __name__ == "__main__":
HOST, PORT = "localhost", 80
server = SocketServer.TCPServer((HOST, PORT), HTTPHandler)
server.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment