[英]How to handle chunked encoding in Python BaseHTTPRequestHandler?
我有以下简单的 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()
当我用 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
传输编码需要什么?
正如您在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
您只需要读取一行,获取下一个块的大小,并同时使用二进制块和后续换行符。
此示例将能够处理带有Content-Length
或Transfer-Encoding: chunked
标头的请求。
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()
注意我选择从SimpleHTTPRequestHandler继承而不是BaseHTTPRequestHandler ,因为然后方法SimpleHTTPRequestHandler.translate_path()
可用于允许客户端选择目标路径(这可能有用与否,取决于用例;我的示例已经写入用它)。
您可以使用curl命令测试两种操作模式,正如您提到的:
# PUT with "Content-Length":
curl --upload-file "file.txt" \
"http://127.0.0.1:8080/uploaded.txt"
# PUT with "Transfer-Encoding: chunked":
curl --upload-file "file.txt" -H "Transfer-Encoding: chunked" \
"http://127.0.0.1:8080/uploaded.txt"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.