Skip to content

Instantly share code, notes, and snippets.

@astromechza
Created July 25, 2019 16:23
Show Gist options
  • Save astromechza/5cc713feaf425b93fd7afd9ae7ab93e2 to your computer and use it in GitHub Desktop.
Save astromechza/5cc713feaf425b93fd7afd9ae7ab93e2 to your computer and use it in GitHub Desktop.
Json http server with GET/POST
#!/usr/bin/env python
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import SocketServer
import json
current = {"hello": "world"}
class S(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Foo-Bar', 'Baz')
self.end_headers()
global current
self.wfile.write(json.dumps(current))
def do_POST(self):
if self.headers.getheader('transfer-encoding', None):
self.send_error(501)
return
data = self.rfile.read(int(self.headers.getheader('content-length', 0)))
print data
global current
current = json.loads(data)
self.send_response(204)
self.end_headers()
self.wfile.flush()
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