create a http server and read the request body as form url encoded in python

Here is a simple example on how to create an HTTP server in Python using the built-in http.server module, and parse a form-urlencoded request body:

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

class RequestHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length).decode('utf-8')
        params = parse_qs(body)

        self.send_response(200)
        self.send_header('Content-Type', 'text/plain; charset=utf-8')
        self.end_headers()

        self.wfile.write(b'Received parameters:\n')
        for key, values in params.items():
            for value in values:
                self.wfile.write(f'{key}={value}\n'.encode('utf-8'))

if __name__ == '__main__':
    server_address = ('', 8080)
    httpd = HTTPServer(server_address, RequestHandler)
    print('Listening on', server_address)
    httpd.serve_forever()
840 chars
24 lines

This code defines a RequestHandler class that extends BaseHTTPRequestHandler, and overrides the do_POST method to extract the form-urlencoded request body from the HTTP request, and parse it into a dictionary using parse_qs from the urllib.parse module.

The parsed parameters are then sent back as a plain text response with keys and values separated by equals signs.

To start the server, we create an instance of HTTPServer and pass it the server address and request handler. Finally, we call serve_forever on the server instance to start accepting incoming requests.

gistlibby LogSnag