Skip to content

Instantly share code, notes, and snippets.

@Terkwood
Forked from bradmontgomery/dummy-web-server.py
Last active August 19, 2018 16:40
Show Gist options
  • Save Terkwood/c461ca86f234abb9dff908a234593326 to your computer and use it in GitHub Desktop.
Save Terkwood/c461ca86f234abb9dff908a234593326 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 python3
"""
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 http.server import BaseHTTPRequestHandler, HTTPServer
import socketserver
import time
class S(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
def do_GET(self):
self._set_headers()
self.wfile.write(("""{ "time": %d }""" % int(time.time())).encode())
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).decode('UTF-8') # <--- Gets the data itself
self._set_headers()
self.wfile.write(("""{ "data": "%s", "time": %d }""" % (post_data, int(time.time()))).encode())
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment