简体   繁体   English

Python TPCServer rfile.read块

[英]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. 我正在编写一个简单的SocketServer.TCPServer请求处理程序( StreamRequestHandler ),它将捕获请求以及标头和消息正文。 This is for faking out an HTTP server that we can use for testing. 这是用于伪造我们可以用于测试的HTTP服务器。

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. 如果我尝试从rfile获取更多而不是存在,则代码会阻塞。 How can I grab all of the request body without knowing its size? 如何在不知道尺寸的情况下抓住所有请求体? In other words, I don't have a Content-Size header. 换句话说,我没有Content-Size标头。

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

Keith's comment is correct. 基思的评论是正确的。 Here's what it looks like 这是它的样子

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM