-
-
Save leixingyu/a9bb23ae3de46db25a952723974fe506 to your computer and use it in GitHub Desktop.
Simple Python 3 HTTP server for logging all GET and POST requests
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
""" | |
Example usage to get/post data on server from client.py | |
``` | |
import requests | |
url = 'http://localhost:8000' | |
def get(url): | |
r = requests.get(url) | |
return r.text | |
def post(url): | |
d = {'key': 'value'} | |
r = requests.post(url, json=d) | |
return r.text | |
``` | |
""" | |
import logging | |
from http.server import BaseHTTPRequestHandler, HTTPServer | |
logging.basicConfig(level=logging.INFO) | |
class ServerDataContainer(object): | |
record = None | |
def get(self): | |
return self.record | |
def post(self, record): | |
self.record = record | |
SERVER_DATA = ServerDataContainer() | |
class MyHandler(BaseHTTPRequestHandler): | |
def _set_response(self): | |
self.send_response(200) | |
self.send_header('Content-type', 'text/html') | |
self.end_headers() | |
def do_GET(self): | |
# server side logging | |
logging.info("GET request,\nPath: %s\nHeaders:\n%s", str(self.path), str(self.headers)) | |
# client side logging | |
# writes to the output stream, respond to the client side | |
# e.g. web browser display or the output of a client script | |
self._set_response() | |
self.wfile.write("GET request: \n last data: {}".format(SERVER_DATA.get()).encode('utf-8')) | |
def do_POST(self): | |
# server side logging | |
logging.info("POST request,\nPath: %s\nHeaders:\n%s", str(self.path), str(self.headers)) | |
# retrieve data from input stream | |
length = int(self.headers['Content-Length']) | |
body = self.rfile.read(length).decode('utf-8') | |
SERVER_DATA.post(body) | |
logging.info("data posted: %s", body) | |
# client side logging | |
# writes to the output stream, respond to the client side | |
# e.g. web browser display or the output of a client script | |
self._set_response() | |
self.wfile.write("POST request: \n data updated: {}".format(body).encode('utf-8')) | |
def run(): | |
addr = ('localhost', 8000) | |
httpd = HTTPServer(addr, MyHandler) | |
logging.info('Starting httpd...\n') | |
try: | |
httpd.serve_forever() | |
except KeyboardInterrupt: | |
pass | |
httpd.server_close() | |
logging.info('Stopping httpd...\n') | |
if __name__ == '__main__': | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment