解决 for chunk in response.iter_content() 报错
使用 stream=True + response.iter_content() 下载文件时,报下面的错误。怀疑是本地的 minio 存储库不支持流式传输导致的异常。因为之前从 oss 和 百度网盘下载没有问题。 然后问了下AI, 确实是这个原因。
unsupported operand type(s) for -: 'float' and 'NoneType'
现在是 except 哪里捕获到异常后直接将 response.content 写入到文件。 但是这样会将整个 response 读入内存。如果文件特别大,就会有内存占满的风险,不知道有没有什么好的办法。
def write(self, f, response, total_size):
chunk_size = 1024 # 每次写入的块大小
compare_size = 0
print('开始写入总体积' + str(total_size))
try:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
f.write(chunk) # 写入本地文件
compare_size = compare_size+chunk_size
self.__completed_size = self.__completed_size + chunk_size
if self.__completed_size > total_size:
self.__completed_size = total_size
print('已完成' + str(self.__completed_size))
self.progress_callback(self.__completed_size, total_size)
except Exception as e:
if f.mode == 'wb':
f.write(response.content)
else:
f.mode = 'wb'
f.write(response.content)
print(e)
我在host文件新加了一行
然后 将资源 url 从 127.0.0.1:9000 改为 minio:9000 之后就支持流式传输了。
expect 捕获到 error ,直接用 logging 拿 error 吧,别写文件里面