2

我有一个简单的基于 BaseHTTPServer 的服务器的以下代码。

class myHandler(BaseHTTPRequestHandler):
    #Handler for the GET requests
    def do_GET(self):
        # Parse the query_str
        query_str = self.path.strip().lower()
        if query_str.startswith("/download?"):
            query_str = query_str[10:]
            opts = urlparse.parse_qs(query_str)

            # Send the html message and download file
            self.protocol_version = 'HTTP/1.1'
            self.send_response(200)
            self.send_header("Content-type", 'text/html')
            self.send_header("Content-length", 1)
            self.end_headers()
            self.wfile.write("0")

            # Some code to do some processing
            # ...
            # -----------

            self.wfile.write("1")

我期待 HTML 页面显示“1”,但它显示“0”。如何通过保持活动更新响应?

4

4 回答 4

6

我相信您将self.protocol_version设置为“HTTP/1.1”为时已晚。您正在 do_GET() 方法中执行此操作,此时您的请求处理程序已经被实例化,并且服务器已经检查了该实例的 protocol_version 属性。

最好在课堂上设置它:

class myHandler(BaseHTTPRequestHandler):
    protocol_version = 'HTTP/1.1'
于 2015-02-19T18:57:32.147 回答
1

不确定您要完成什么,但如果您想发送 1,您需要将 content-length 设置为 2 或完全删除它。1 不会覆盖 0,所以你会看到 01。

于 2014-11-22T21:32:01.650 回答
0

https://docs.python.org/2/library/basehttpserver.html

协议版本

这指定了响应中使用的 HTTP 协议版本。如果设置为 'HTTP/1.1',服务器将允许 HTTP 持久连接;但是,您的服务器必须在其对客户端的所有响应中包含准确的 Content-Length 标头(使用 send_header())。为了向后兼容,该设置默认为“HTTP/1.0”。

于 2014-12-14T09:41:30.543 回答
0

我面临同样的问题。我尝试在我的 do_METHOD() 函数中设置协议版本,但它不起作用。我的代码看起来像这样。

def _handle(self, method):
    self.protocol_version = "HTTP/1.1"
    # some code here

def do_GET(self):
    self._handle("GET")

我使用 ss 和 tcpdump 来检测网络,最后发现服务器将在发送响应后重置连接,尽管它使用 http/1.1。

所以我尝试在从标准库类继承的类下设置协议版本,它可以工作。由于时间成本,我不深入研究源代码。希望它适用于其他人。

于 2021-03-03T07:38:31.697 回答