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

To create a HTTP server in Python, you can make use of the built-in http.server module. Here's an example of how to create an HTTP server and read the request body as text in Python:

main.py
from http.server import BaseHTTPRequestHandler, HTTPServer


class RequestHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length).decode('utf-8')
        self.send_response(200)
        self.end_headers()
        response = 'Received request body: {}'.format(body)
        self.wfile.write(response.encode('utf-8'))

def run_server():
    server_address = ('', 8000)
    httpd = HTTPServer(server_address, RequestHandler)
    httpd.serve_forever()

if __name__ == '__main__':
    run_server()
601 chars
20 lines

In this example, we define a RequestHandler class that inherits from BaseHTTPRequestHandler. We override the do_POST method to capture POST requests and read the request body using the rfile attribute. We then send a 200 response code with the send_response method, and write the response body with the wfile attribute.

Lastly, we define a run_server function that creates an instance of our HTTP server and starts it with the serve_forever method. When you run this script, the server will listen on port 8000 by default. When a POST request is received, the server will respond with the request body as text.

related categories

gistlibby LogSnag