Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
518
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  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.  
  10. class S(BaseHTTPRequestHandler):
  11.     def _set_response(self):
  12.         self.send_response(200)
  13.         self.send_header('Content-type', 'text/html')
  14.         self.end_headers()
  15.  
  16.     def do_GET(self):
  17.         logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
  18.         self._set_response()
  19.         self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))
  20.  
  21.     def do_POST(self):
  22.         content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
  23.         post_data = self.rfile.read(content_length) # <--- Gets the data itself
  24.         logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",
  25.                 str(self.path), str(self.headers), post_data.decode('utf-8'))
  26.  
  27.         self._set_response()
  28.         self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))
  29.  
  30. def run(server_class=HTTPServer, handler_class=S, port=8080):
  31.     logging.basicConfig(level=logging.INFO)
  32.     server_address = ('', port)
  33.     httpd = server_class(server_address, handler_class)
  34.     logging.info('Starting httpd...\n')
  35.     try:
  36.         httpd.serve_forever()
  37.     except KeyboardInterrupt:
  38.         pass
  39.     httpd.server_close()
  40.     logging.info('Stopping httpd...\n')
  41.  
  42. if __name__ == '__main__':
  43.     from sys import argv
  44.  
  45.     if len(argv) == 2:
  46.         run(port=int(argv[1]))
  47.     else:
  48.         run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement