Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- #
- # Request
- #
- class Request(object):
- def __init__(self, request_str):
- request_str_lines = request_str.split("\r\n")
- first_line = request_str_lines[0].split(" ")
- settings_lines = map(lambda line:line.split(": "), request_str_lines[1:-2])
- self.http_version = first_line[2][-3:]
- self.method = first_line[0]
- self.path = first_line[1]
- self.settings = {setting[0]:setting[1] for setting in settings_lines}
- #
- # Response
- #
- class Response(object):
- def __init__(self, http_version):
- self.text = "HTTP/%s {http_code} OK\r\nContent-Type: {content_type}\r\nContent-Length: {content_length}\r\n\r\n" % http_version
- #
- # Route
- #
- class Route(object):
- # TODO: Allow paths to be list or tuple not just list
- def __init__(self, paths, output, content_type):
- self.content_type = content_type
- self.paths = map(lambda p:str(p),paths) if type(paths) is list else [str(paths)]
- self.output = output
- def has_path(self, path_needle):
- path_needle = str(path_needle)
- for path in self.paths:
- if compare_paths(path, path_needle):
- return True
- return False
- def compare_paths(first, second):
- if first == second:
- return True
- else:
- return bool(re.match(first+"/", second+"/"))
- return False
- #
- # handle_request() returns None
- # TODO: Make this function not suck
- #
- def handle_request(client, address, routes):
- request = Request(client.recv(512))
- response = Response(request.http_version)
- for route in routes[request.method.upper()]:
- if route.has_path(request.path):
- output_str = str(route.output(request))
- response.text = response.text.format(http_code="200", content_type=route.content_type, content_length=len(output_str))
- response.text = str().join([response.text, output_str])
- break
- else:
- response.text = response.text.format(http_code="404", content_type="text/plain", content_length="13")
- response.text = str().join([response.text, "404 Not Found"])
- client.send(response.text)
- client.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement