create a http server with a post route in python

To create a simple HTTP server with a POST route in Python, you can use the built-in http.server module. Here's an example:

main.py
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse
import cgi

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):

    def do_POST(self):
        parsed_path = urlparse(self.path)
        content_length = int(self.headers.get('Content-Length', 0))
        post_data = self.rfile.read(content_length)
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'POST request received:\n')
        self.wfile.write(post_data)

def run(server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler, port=8000):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print(f'Starting httpd on port {port}...')
    httpd.serve_forever()

if __name__ == "__main__":
    run()
781 chars
24 lines

This creates a server that listens on port 8000 and logs any POST requests it receives. Note that this example is for demonstration purposes only and does not include any security or error handling measures that would be necessary in a production environment.

gistlibby LogSnag