serve 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/usr/bin/python
  2. import sys, pyserv, testserv
  3. # Change this to change which server class gets used. Should be a subclass of pyserv.HTTPServer.
  4. server = testserv.TestServ()
  5. # Example registration (in server __init__ method)
  6. # self.register("GET",lambda m,p,h: pyserv.abort(418))
  7. # The above will make any GET request return the I'm a Teapot code.
  8. # Distance from end of string to literal "HTTP". Should be 8 in all requests.
  9. def httpDistance(l):
  10. return (l[::-1].find("PTTH"))+len("PTTH")
  11. # Read all lines of data sent to us by browser/client
  12. inlines = []
  13. a = sys.stdin.readline().rstrip()
  14. while a:
  15. inlines.append(a)
  16. a = sys.stdin.readline().rstrip()
  17. # Validate HTTP request
  18. # In all valid HTTP requests, "HTTP/X.X" is 8 characters from the end.
  19. if httpDistance(inlines[0])!=8:
  20. print(pyserv.abort(400))
  21. # Parse headers
  22. headers = dict()
  23. for l in inlines[1:]:
  24. p = l.split(": ",1)
  25. if p[0] in headers:
  26. continue
  27. headers[p[0]] = p[1]
  28. # Parse request
  29. method, path, version = inlines[0].split(" ")
  30. # If the server doesn't have the method, it isn't implemented.
  31. if not server.hasMethod(method):
  32. print(pyserv.abort(501))
  33. if method=="POST":
  34. # Read query-string and call function
  35. print(server.methods[method](method, path, headers, sys.stdin.read(int(headers["Content-Length"]))))
  36. else:
  37. # Just call the function
  38. print(server.methods[method](method, path, headers))