Skip to content

Instantly share code, notes, and snippets.

@kyanny
Last active Oct 12, 2021
Embed
What would you like to do?
# ref. https://gist.github.com/mdonkers/63e115cc0c79b4f6b8b3a6b797e485c7
# ref. https://stackoverflow.com/questions/54607547/read-http-request-data-in-python-3
import http.server
import socketserver
import logging
import os
import urllib.parse
PORT = os.getenv("PORT", 8080)
class Server(socketserver.TCPServer):
allow_reuse_address = True
class Handler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
res = []
res.append('=' * 80)
res.append(f'GET {self.path}')
res.append(str(self.headers))
parsed_path = urllib.parse.urlparse(self.path)
res.append(str(parsed_path))
body = "\n".join(res)
logging.info(body)
self.send_response(200)
self.end_headers()
self.wfile.write(bytes(body, 'utf8'))
def do_POST(self):
res = []
res.append('=' * 80)
res.append(f'POST {self.path}')
res.append(str(self.headers))
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
res.append(str(post_data))
body = "\n".join(res)
logging.info(body)
self.send_response(200)
self.end_headers()
self.wfile.write(bytes(body, 'utf8'))
logging.basicConfig(level=logging.INFO)
with Server(("", PORT), Handler) as httpd:
print(f"http://0.0.0.0:{PORT}")
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment