Last active
August 9, 2018 18:02
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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