Here's an example of how to create an HTTP server and read the request body in Python using the built-in http.server
module:
main.py625 chars18 lines
In this example, we define a custom request handler class MyServer
that inherits from BaseHTTPRequestHandler
and overrides the do_POST()
method to handle POST
requests.
Inside this method, we read the Content-Length
header to determine the length of the request body, then read that many bytes from the request using self.rfile.read()
.
We then send a 200 OK
response with self.send_response()
and self.end_headers()
, followed by a simple response message containing the received request body. Finally, we send this message to the client using self.wfile.write()
.
When we run this script, it will start a web server listening on http://localhost:8000
. You can test it by sending a POST request to this URL with a request body using a tool like curl
or httpie
. For example:
main.py383 chars17 lines
gistlibby LogSnag