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

Here's an example code to create a HTTP server in Python and reading the request body as multipart form data using the built-in http.server and cgi modules:

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

class MyRequestHandler(BaseHTTPRequestHandler):

    def do_POST(self):
        ctype, pdict = cgi.parse_header(self.headers.get('content-type'))
        
        if ctype == 'multipart/form-data':
            # Read the request body as multipart form data
            fields = cgi.parse_multipart(self.rfile, pdict)
            
            # Print the form data fields
            for key, value in fields.items():
                print('%s=%s' % (key, value))
        
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(b'OK')

def run_server(port=8000):
    server_address = ('', port)
    httpd = HTTPServer(server_address, MyRequestHandler)
    print('HTTP server is running on port %d...' % port)
    httpd.serve_forever()

if __name__ == '__main__':
    run_server()
933 chars
30 lines

This code defines a custom request handler (MyRequestHandler) by extending http.server.BaseHTTPRequestHandler class. In the do_POST() method, it reads the request body as multipart form data using the cgi.parse_multipart() method and prints the fields. Finally, it sends a response with 200 OK status code.

The run_server() function starts the HTTP server on the given port (default is 8000) using HTTPServer class from http.server module. When the server receives a request, it calls MyRequestHandler to handle the request.

You can run this code from the command line by running python server.py. Then, you can send a POST request with multipart form data using a tool like curl:

main.py
curl -X POST -H "Content-Type: multipart/form-data" -F "name=John" -F "age=30" http://localhost:8000
101 chars
2 lines

gistlibby LogSnag