如何在 Python BaseHTTPRequestHandler 中处理分块编码?

use*_*175 7 python http chunked

我有以下简单的 Web 服务器,利用 Python 的http模块:

import http.server
import hashlib


class RequestHandler(http.server.BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def do_PUT(self):
        md5 = hashlib.md5()

        remaining = int(self.headers['Content-Length'])
        while True:
            data = self.rfile.read(min(remaining, 16384))
            remaining -= len(data)
            if not data or not remaining:
                break
            md5.update(data)
        print(md5.hexdigest())

        self.send_response(204)
        self.send_header('Connection', 'keep-alive')
        self.end_headers()


server = http.server.HTTPServer(('', 8000), RequestHandler)
server.serve_forever()
Run Code Online (Sandbox Code Playgroud)

当我使用curl上传文件时,效果很好:

curl -vT /tmp/test http://localhost:8000/test

由于文件大小是预先已知的,curl 将发送一个Content-Length: 5标头,因此我可以知道应该从套接字读取多少内容。

但如果文件大小未知,或者客户端决定使用chunked传输编码,则此方法会失败。

可以使用以下命令进行模拟:

curl -vT /tmp/test -H "Transfer-Encoding: chunked" http://localhost:8000/test

如果我从self.rfile该块的过去读取,它将永远等待并挂起客户端,直到它断开 TCP 连接,其中self.rfile.read将返回一个空数据,然后它会跳出循环。

chunked扩展上面的示例以支持传输编码需要什么?

j1e*_*elo 9

正如您在Transfer-Encoding的描述中看到的,分块传输将具有以下形状:

chunk1_length\r\n
chunk1 (binary data)
\r\n
chunk2_length\r\n
chunk2 (binary data)
\r\n
0\r\n
\r\n
Run Code Online (Sandbox Code Playgroud)

您只需读取一行,获取下一个块的大小,然后使用二进制块后续换行符。

此示例将能够处理带有Content-LengthTransfer-Encoding: chunked标头的请求。

chunk1_length\r\n
chunk1 (binary data)
\r\n
chunk2_length\r\n
chunk2 (binary data)
\r\n
0\r\n
\r\n
Run Code Online (Sandbox Code Playgroud)

注意我选择继承SimpleHTTPRequestHandler而不是BaseHTTPRequestHandler,因为这样该方法SimpleHTTPRequestHandler.translate_path()可用于允许客户端选择目标路径(这可能有用也可能没用,具体取决于用例;我的示例已经编写为使用它)。

正如您所提到的,您可以使用curl命令测试两种操作模式:

from http.server import HTTPServer, SimpleHTTPRequestHandler

PORT = 8080

class TestHTTPRequestHandler(SimpleHTTPRequestHandler):
    def do_PUT(self):
        self.send_response(200)
        self.end_headers()

        path = self.translate_path(self.path)

        if "Content-Length" in self.headers:
            content_length = int(self.headers["Content-Length"])
            body = self.rfile.read(content_length)
            with open(path, "wb") as out_file:
                out_file.write(body)
        elif "chunked" in self.headers.get("Transfer-Encoding", ""):
            with open(path, "wb") as out_file:
                while True:
                    line = self.rfile.readline().strip()
                    chunk_length = int(line, 16)

                    if chunk_length != 0:
                        chunk = self.rfile.read(chunk_length)
                        out_file.write(chunk)

                    # Each chunk is followed by an additional empty newline
                    # that we have to consume.
                    self.rfile.readline()

                    # Finally, a chunk size of 0 is an end indication
                    if chunk_length == 0:
                        break

httpd = HTTPServer(("", PORT), TestHTTPRequestHandler)

print("Serving at port:", httpd.server_port)
httpd.serve_forever()
Run Code Online (Sandbox Code Playgroud)

  • 您的块处理中有一个小错误。请在“chunk_length == 0”检查之后添加“self.rfile.readline()”(循环中断之前的检查),因为线路上仍然有“\r\n”字节来结束块流。如果有人(像我一样)想要持久连接,下次框架调用“handle_one_request”时,它将读取线路上剩余的两个字节,认为出现问题,然后关闭连接。不过,感谢您的代码,它让我朝着正确的方向前进。 (2认同)