erinx

a python http server

Dec 5th, 2016
550
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 KB | None | 0 0
  1. #!/usr/bin/env python
  2. """
  3. Very simple HTTP server in python.
  4. Usage::
  5.    ./dummy-web-server.py [<port>]
  6. Send a GET request::
  7.    curl http://localhost
  8. Send a HEAD request::
  9.    curl -I http://localhost
  10. Send a POST request::
  11.    curl -d "foo=bar&bin=baz" http://localhost
  12. """
  13. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
  14. import SocketServer
  15.  
  16. class S(BaseHTTPRequestHandler):
  17.     def _set_headers(self):
  18.         self.send_response(200)
  19.         self.send_header('Content-type', 'text/html')
  20.         self.end_headers()
  21.  
  22.     def do_GET(self):
  23.         self._set_headers()
  24.         self.wfile.write("<html><body><h1>hi!</h1></body></html>")
  25.  
  26.     def do_HEAD(self):
  27.         self._set_headers()
  28.        
  29.     def do_POST(self):
  30.         # Doesn't do anything with posted data
  31.         content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
  32.         post_data = self.rfile.read(content_length) # <--- Gets the data itself
  33.         self._set_headers()
  34.         self.wfile.write("<html><body><h1>POST!</h1></body></html>")
  35.        
  36. def run(server_class=HTTPServer, handler_class=S, port=80):
  37.     server_address = ('', port)
  38.     httpd = server_class(server_address, handler_class)
  39.     print 'Starting httpd...'
  40.     httpd.serve_forever()
  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