Advertisement
Guest User

Untitled

a guest
Dec 5th, 2012
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 KB | None | 0 0
  1. import re
  2.  
  3. #
  4. # Request
  5. #
  6. class Request(object):
  7.     def __init__(self, request_str):
  8.         request_str_lines = request_str.split("\r\n")
  9.         first_line = request_str_lines[0].split(" ")
  10.         settings_lines = map(lambda line:line.split(": "), request_str_lines[1:-2])
  11.  
  12.         self.http_version = first_line[2][-3:]
  13.         self.method = first_line[0]
  14.         self.path = first_line[1]
  15.         self.settings = {setting[0]:setting[1] for setting in settings_lines}
  16.  
  17. #
  18. # Response
  19. #
  20. class Response(object):
  21.     def __init__(self, http_version):
  22.         self.text = "HTTP/%s {http_code} OK\r\nContent-Type: {content_type}\r\nContent-Length: {content_length}\r\n\r\n" % http_version
  23.  
  24. #
  25. # Route
  26. #
  27. class Route(object):
  28.     # TODO: Allow paths to be list or tuple not just list
  29.     def __init__(self, paths, output, content_type):
  30.         self.content_type = content_type
  31.         self.paths = map(lambda p:str(p),paths) if type(paths) is list else [str(paths)]
  32.         self.output = output
  33.  
  34.     def has_path(self, path_needle):
  35.         path_needle = str(path_needle)
  36.         for path in self.paths:
  37.             if compare_paths(path, path_needle):
  38.                 return True
  39.         return False
  40.  
  41. def compare_paths(first, second):
  42.     if first == second:
  43.         return True
  44.     else:
  45.         return bool(re.match(first+"/", second+"/"))
  46.     return False
  47.  
  48. #
  49. # handle_request() returns None
  50. # TODO: Make this function not suck
  51. #
  52. def handle_request(client, address, routes):
  53.     request = Request(client.recv(512))
  54.     response = Response(request.http_version)
  55.  
  56.     for route in routes[request.method.upper()]:
  57.         if route.has_path(request.path):
  58.             output_str = str(route.output(request))
  59.             response.text = response.text.format(http_code="200", content_type=route.content_type, content_length=len(output_str))
  60.             response.text = str().join([response.text, output_str])
  61.             break
  62.     else:
  63.         response.text = response.text.format(http_code="404", content_type="text/plain", content_length="13")
  64.         response.text = str().join([response.text, "404 Not Found"])
  65.  
  66.     client.send(response.text)
  67.     client.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement