Created
March 31, 2010 16:59
-
-
Save etianen/350574 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys, itertools | |
# Supported HTTP methods. | |
GET = "GET" | |
POST = "POST" | |
# A parsed HTTP request. | |
class Request(object): | |
def __init__(self, method, path, protocol, headers): | |
self.method = method | |
self.path = path | |
self.protocol = protocol | |
self.headers = headers | |
# A parser for a HTTP request. | |
def parse_header(line): | |
return (item.strip() for item in line.split(":", 1)) | |
def parse(input): | |
lines = iter(input) | |
method, path, protocol = next(lines).split() | |
headers = dict(parse_header(line) for line in itertools.takewhile(lambda line: line != "", lines)) | |
return Request(method, path, protocol, headers) | |
# Known HTTP status messages. | |
status_messages = {200: "OK", | |
404: "Not Found", | |
500: "Server Error"} | |
# A HTTP response. | |
class HttpResponse(object): | |
def __init__(self, code, body): | |
self.code = code | |
self.body = body | |
def __str__(self): | |
return "%i %s\n\n%s" % (self.code, status_messages.get(self.code, ""), self.body) | |
# Request handler. | |
def request_handler(request): | |
body = "<h1>Result for a %s request to http://%s%s</h1>\n%s" % (request.method, request.headers["Host"], request.path, request.headers) | |
return HttpResponse(200, body) | |
# Main server method used to process a single request. | |
def processRequest(input): | |
return str(request_handler(parse(input))) | |
if __name__ == "__main__": | |
print processRequest(sys.stdin) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment