Skip to content

Instantly share code, notes, and snippets.

@tdwong
Forked from bradmontgomery/dummy-web-server.py
Last active April 28, 2016 06:45
Show Gist options
  • Save tdwong/0bfe8111ccd367c5b1d0b8911ce3fd95 to your computer and use it in GitHub Desktop.
Save tdwong/0bfe8111ccd367c5b1d0b8911ce3fd95 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.
#!/usr/bin/env python
#https://gist.github.com/bradmontgomery/2219997
"""
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):
print "GET request"
self._set_headers()
self.wfile.write("<html><body><h1>hi! GET!</h1></body></html>")
def do_HEAD(self):
print "HEAD request"
self._set_headers()
#http://stackoverflow.com/questions/4233218/python-basehttprequesthandler-post-variables
def parse_POST(self):
# extract the parameter
from urlparse import parse_qs
# check if paramater exists
if self.path.find('?') > 0:
pathvars = parse_qs(self.path.split('?',1)[-1], keep_blank_values=1)
else:
pathvars = {}
# read http payload
from cgi import parse_header, parse_multipart
ctype, pdict = parse_header(self.headers['content-type'])
if ctype == 'multipart/form-data':
postvars = parse_multipart(self.rfile, pdict)
elif ctype == 'application/x-www-form-urlencoded':
length = int(self.headers['content-length'])
postvars = self.rfile.read(length)
else:
postvars = {}
#
# return collected information
#
return pathvars, postvars
def do_POST(self):
# parse and print POST data
pathvars, postvars = self.parse_POST()
#
self._set_headers()
self.wfile.write("<html><body><h1>POST!</h1></body></html>")
print "POST params:", pathvars
print "POST content:", postvars
## port=80 requires root permission
## def run(server_class=HTTPServer, handler_class=S, port=80):
def run(server_class=HTTPServer, handler_class=S, port=8080):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print 'Starting httpd... on port', port
httpd.serve_forever()
if __name__ == "__main__":
from sys import argv
try:
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
except KeyboardInterrupt:
print "stopped by keyboard interrupt..."
except Exception as e:
print e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment