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
相关产品推荐
相关产品推荐

