testserv.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import pyserv, sys
  2. # Adding response headers to this list will put them in any response that doesn't need specific headers.
  3. DEFAULT_RESPONSE_HEADERS = dict(Server=pyserv.VERSION)
  4. class TestServ(pyserv.HTTPServer):
  5. def __init__(self):
  6. # Initialize base class.
  7. super().__init__()
  8. # Register GET and POST methods.
  9. self.register("GET",self.do_GET)
  10. self.register("POST",self.do_POST)
  11. # Add registries for other reasons
  12. self.contents = dict()
  13. self.mime = dict()
  14. self.cgi = dict()
  15. self.post = dict()
  16. # Add index.html content to be statically served.
  17. with open("index.html") as f:
  18. self.registerPage("/",[l.rstrip() for l in f],"text/html")
  19. self.registerPage("/index.html",self.contents["/"],"text/html")
  20. # Register greeting form (from bottom of index.html) as POST /.
  21. self.registerPost("/",self.greetingform)
  22. def registerPage(self,path,content,mime="text/plain"):
  23. self.contents[path] = content
  24. self.mime[path] = mime
  25. def registerCGI(self,path,func):
  26. self.cgi[path]=func
  27. def registerPost(self,path,func):
  28. self.post[path] = func
  29. def greetingform(self,path,headers,data):
  30. with open("greetings.html") as f:
  31. return 200, DEFAULT_RESPONSE_HEADERS, [l.rstrip().format(pyserv.lazySan(data['name'][0])) for l in f]
  32. def do_GET(self,method,path,headers):
  33. resp_headers = dict(Server=pyserv.VERSION)
  34. contents = []
  35. if not path.startswith("/cgi/"): # CGI paths are relative to /cgi/.
  36. try:
  37. contents = self.contents[path] # Get static path.
  38. resp_headers["Content-Type"] = self.mime[path]
  39. except:
  40. return pyserv.abort(404)
  41. else:
  42. try:
  43. contents = self.cgi[path[len("/cgi"):]](path,headers) # Run CGI page function.
  44. except IndexError:
  45. return pyserv.abort(404) # If path doesn't exist, we want to return 404
  46. except:
  47. return pyserv.abort(500) # If something else happens, it's an internal error.
  48. return self.formatResponse(200,resp_headers,contents) # Send contents along.
  49. def do_POST(self,m,path,headers,data):
  50. if path in self.post:
  51. try:
  52. # CGI functions return response code, response headers, and contents.
  53. respcode, resp_headers, contents = self.post[path](path,headers,pyserv.unquote(data))
  54. # This data is directly passed into formatResponse to get a formatted response.
  55. return self.formatResponse(respcode,resp_headers,contents)
  56. except pyserv.Abort404: # Abort404 error is a signal
  57. return pyserv.abort(404)
  58. except: # If something else goes wrong, it's an internal error.
  59. return pyserv.abort(500)
  60. return pyserv.abort(405) # If path isn't in self.post, we aren't going to bother asking GET for it.