Python TPCServer rfile.read blocks

2019-04-08 00:43发布

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

1条回答
Lonely孤独者°
2楼-- · 2019-04-08 01:09

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

     length = int(self.headers.getheader('content-length'))
     data = self.rfile.read(length)
查看更多
登录 后发表回答