Python TPCServer rfile.read blocks

I am writing a simple request handler SocketServer.TCPServer( StreamRequestHandler) that will capture the request along with the headers and body of the message. This is to fake an HTTP server that we can use for testing.

I have no problem capturing a query string or headers.

If I try to extract more from rfilethan there are blocks of code. How can I capture the entire body of a request without knowing its size? In other words, I have no title Content-Size.

Here is a snippet of what I have now:

def _read_request_line(self):
    server.request_line = self.rfile.readline().rstrip('\r\n')

def _read_headers(self):
    headers = []
    for line in self.rfile:
        line = line.rstrip('\r\n')
        if not line:
            break
        parts = line.split(':', 1)
        header = (parts[0].strip(), parts[0].strip())
        headers.append(header)
    server.request_headers = headers

def _read_content(self):
    server.request_content = self.rfile.read()  # blocks
+5
source share
1 answer

Whale's comment is correct. That's what it looks like

     length = int(self.headers.getheader('content-length'))
     data = self.rfile.read(length)
+9
source

All Articles