Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python TPCServer rfile.read blocks

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

I have no trouble grabbing the request line or the headers.

If I try to grab more from the rfile than exists, the code blocks. How can I grab all of the request body without knowing its size? In other words, I don't have a Content-Size header.

Here's 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
like image 333
Travis Parks Avatar asked Sep 27 '12 16:09

Travis Parks


1 Answers

Keith's comment is correct. Here's what it looks like

     length = int(self.headers.getheader('content-length'))
     data = self.rfile.read(length)
like image 171
Jim Carroll Avatar answered Sep 29 '22 04:09

Jim Carroll