Skip to content

Instantly share code, notes, and snippets.

@bafu
Created February 15, 2016 14:28
Show Gist options
  • Save bafu/86cf921a6bc816475674 to your computer and use it in GitHub Desktop.
Save bafu/86cf921a6bc816475674 to your computer and use it in GitHub Desktop.
Simple POST server
#!/usr/bin/python3
# Source: http://stackoverflow.com/questions/13146064/simple-python-webserver-to-save-file
#
# Usage:
# # Server
# $ python3 -m webserver
#
# # Client: POST
# import requests
# requests.post('http://localhost:5566/post', json={'key':'value'})
from os import curdir
from os.path import join as pjoin
from http.server import BaseHTTPRequestHandler, HTTPServer
class StoreHandler(BaseHTTPRequestHandler):
store_path = pjoin(curdir, 'store.json')
def do_GET(self):
if self.path == '/get':
result = pjoin(curdir, 'results.json')
#with open(self.store_path) as f:
with open(result) as f:
self.send_response(200)
self.send_header('Content-type', 'text/json')
self.end_headers()
self.wfile.write(f.read().encode())
def do_POST(self):
if self.path == '/post':
length = self.headers['content-length']
data = self.rfile.read(int(length))
with open(self.store_path, 'w') as f:
f.write(data.decode())
#self.send_response(200)
with open(self.store_path) as f:
self.send_response(200)
self.send_header('Content-type', 'text/json')
self.end_headers()
self.wfile.write(f.read().encode())
server = HTTPServer(('', 5566), StoreHandler)
server.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment