Skip to content

Instantly share code, notes, and snippets.

@jimwhitfield
Last active August 9, 2018 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimwhitfield/61c75cf7800ca61d5eb008ddd906f820 to your computer and use it in GitHub Desktop.
Save jimwhitfield/61c75cf7800ca61d5eb008ddd906f820 to your computer and use it in GitHub Desktop.
Web server to accept JSON-formatted HTTP POSTs and pretty-print the payload
#!/usr/bin/python2
# Derived from https://gist.github.com/bradmontgomery/2219997#file-dummy-web-server-py-L26
# Added the feature to read the post body and print it to console.
# Not useful if the post body isn't json
# Usage::
# ./print_json_posts.py [<port>]
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import SocketServer
import json
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):
# Pretty print the posted data
length = self.headers["Content-Length"]
bytes = self.rfile.read(int(length))
print "POST payload: length",length
# print bytes
print json.dumps(json.loads(bytes), sort_keys=True,
indent=4, separators=(',', ': '))
self._set_headers()
self.wfile.write("<html><body><h1>POST!</h1></body></html>")
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