Skip to content

Instantly share code, notes, and snippets.

@mendhak
Forked from bradmontgomery/dummy-web-server.py
Created August 25, 2017 21:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mendhak/eb22f70adf0f7e694bbcb4ef0b11b5a8 to your computer and use it in GitHub Desktop.
Save mendhak/eb22f70adf0f7e694bbcb4ef0b11b5a8 to your computer and use it in GitHub Desktop.
a minimal http server in python. Responds to GET, HEAD, POST requests, but will fail on anything else. Also prints POST body
#!/usr/bin/env python
"""
Very simple HTTP server in python.
Usage::
./dummy-web-server.py [<port>]
Send a GET request::
curl http://localhost
Send a HEAD request::
curl -I http://localhost
Send a POST request::
curl -d "foo=bar&bin=baz" http://localhost
"""
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import SocketServer
class S(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
self._set_headers()
self.wfile.write("<html><body><h1>hi!</h1></body></html>")
def do_HEAD(self):
self._set_headers()
def do_POST(self):
# Doesn't do anything with posted data
content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
post_data = self.rfile.read(content_length) # <--- Gets the data itself
print post_data # <-- Print post data
self.wfile.write("<html><body><h1>POST!</h1><pre>" + post_data + "</pre></body></html>")
self._set_headers()
def run(server_class=HTTPServer, handler_class=S, port=80):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print 'Starting httpd...'
httpd.serve_forever()
if __name__ == "__main__":
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
@talbz
Copy link

talbz commented Jan 19, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment