Schrey
Schrey

Reputation: 13

Why does the BaseHTTPRequestHandler rfile.read() delay execution?

I am making a simple server in python using http.server package. My goal is to log the data of POST from client to server. The problem I am having is rfile.read() is delaying execution until next POST request or if the connection is disconnected.

However this problem doesn't occur if the length of the content is specified as the argument in rfile.read().

The below is the subclass for BaseHTTPRequestHandler of http.server.

class Reqhand(BaseHTTPRequestHandler):

    def do_POST(self):
        self.send_response(200)
        #The lines below don't execute until the next POST req
        req = self.rfile.read()
        print(req)

The below code executes as intended in a single POST request.

class Reqhand(BaseHTTPRequestHandler):

    def do_POST(self):
        self.send_response(200)
        content_len = int(self.headers.get_all('Content-Length')[0])
        req = self.rfile.read(content_len)
        print(req)

Upvotes: 1

Views: 46

Answers (1)

Mohsen Khosroanjam
Mohsen Khosroanjam

Reputation: 521

This happens because rfile.read() waits indefinitely until the client closes the connection or signals the end of the data stream. This behavior is by design when the Content-Length header is not provided, as the server does not know how much data to expect.

To handle this, you should always rely on the Content-Length header in HTTP post requests to determine how much data to read.

Make sure the client sends the Content-Length header in its post request.

Upvotes: 2

Related Questions