httpgetpost-debug.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/usr/bin/env python3
  2. """
  3. Very simple HTTP server in python for logging requests
  4. Usage::
  5. ./server.py [<port>]
  6. """
  7. from http.server import BaseHTTPRequestHandler, HTTPServer
  8. import logging
  9. class S(BaseHTTPRequestHandler):
  10. def _set_response(self):
  11. self.send_response(200)
  12. self.send_header('Content-type', 'text/html')
  13. self.end_headers()
  14. def do_GET(self):
  15. logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
  16. self._set_response()
  17. self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))
  18. def do_POST(self):
  19. content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
  20. post_data = self.rfile.read(content_length) # <--- Gets the data itself
  21. logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",
  22. str(self.path), str(self.headers), post_data.decode('utf-8'))
  23. self._set_response()
  24. self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))
  25. def run(server_class=HTTPServer, handler_class=S, port=8080):
  26. logging.basicConfig(level=logging.INFO)
  27. server_address = ('', port)
  28. httpd = server_class(server_address, handler_class)
  29. logging.info('Starting httpd...\n')
  30. try:
  31. httpd.serve_forever()
  32. except KeyboardInterrupt:
  33. pass
  34. httpd.server_close()
  35. logging.info('Stopping httpd...\n')
  36. if __name__ == '__main__':
  37. from sys import argv
  38. if len(argv) == 2:
  39. run(port=int(argv[1]))
  40. else:
  41. run()