Created
July 25, 2019 16:23
-
-
Save astromechza/5cc713feaf425b93fd7afd9ae7ab93e2 to your computer and use it in GitHub Desktop.
Json http server with GET/POST
This file contains 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/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