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

To create an HTTP server in Python, you can make use of the built-in http.server module. To read the request body as form data, you can use the cgi module. Here's an example code snippet:

main.py
from http.server import BaseHTTPRequestHandler, HTTPServer
import cgi

# define a handler class
class RequestHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        # read the form data from the request body
        form = cgi.FieldStorage(
            fp=self.rfile,
            headers=self.headers,
            environ={'REQUEST_METHOD': 'POST'}
        )

        # extract the data from the form fields
        name = form["name"].value
        email = form["email"].value

        # send a response
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(f"Hello {name}, your email is {email}".encode())

# create a server instance
port = 8080
server_address = ('', port)
httpd = HTTPServer(server_address, RequestHandler)
print(f"Server running on port {port}")

# start the server
httpd.serve_forever()
901 chars
32 lines

In this example, we define a custom request handler class that inherits from BaseHTTPRequestHandler. We override the do_POST method to extract the form data from the request body using the cgi.FieldStorage class. We then send a response back to the client with the extracted data. Finally, we create an HTTP server instance on port 8080 and start it using the serve_forever method.

gistlibby LogSnag