Python TPCServer rfile.read blocks

拜拜、爱过 提交于 2019-12-05 22:35:39

问题


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:


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

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


来源:https://stackoverflow.com/questions/12626427/python-tpcserver-rfile-read-blocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!