You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.6使用Tornado实现REST GET返回文件时校验和不一致问题

Tornado GET接口下载文件校验和不一致问题排查

问题背景

基于Tornado实现REST GET接口返回文件时,每次下载得到的文件校验和均不相同,需要定位是返回分片顺序出错还是其他诱因,当前使用curl工具进行文件下载。

原有接口实现代码

async def get(self, filename):
    chunkSize = 1024 * 1024 * 1 # 1 Mib
    with open(filename, 'rb') as f:
        while True:
            chunk = f.read(chunkSize)
            if not chunk:
                break
            try:
                self.write(chunk) # write the chunk to the response
                await self.flush()# send the chunk to the client
            except iostream.StreamClosedError:
                break
            finally:
                del chunk
                await gen.sleep(0.000000001)
    self.finish()

根因定位

本地测试后确认问题出在curl命令参数,使用的curl命令携带-i参数,该参数会将HTTP响应头信息写入输出文件开头,导致下载的文件比原文件多出了响应头内容,因此校验和不一致,与接口分片返回逻辑无关。
使用的错误curl命令如下:

curl --user test -i -X GET http://localhost:8085/download/testfile.dat --output testfile.dat

解决方案

方案一:修正curl命令参数

移除-i参数即可正常下载,修改后的命令:

curl --user test -X GET http://localhost:8085/download/testfile.dat --output testfile.dat

方案二:使用wget工具下载

改用无额外响应头输出逻辑的wget工具下载也可解决问题,对应命令:

wget --http-user=test --http-passwd=test http://localhost:8085/download/testfile.dat

代码优化建议

原有代码中await gen.sleep(0.000000001)无实际业务价值,还会增加不必要的调度开销,可以直接删除。

内容的提问来源于stack exchange,提问作者user1728363

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 03:54:02