【发布时间】:2021-06-18 17:42:54
【问题描述】:
我正在使用请求来下载响应,如下所示:
resp = requests.get(url, stream=True)
# to local file
with open(valid_filename, "wb") as file_writer:
for chunk in resp.iter_content(1024):
file_writer.write(chunk)
# to google bucket blob
blob = gs_bucket.blob(filename)
with blob.open("wb") as blob_writer:
for chunk in resp.iter_content(1024):
blob_writer.write(chunk)
这两种方法都会导致在迭代响应时重复输出 chunk_size (1024)。
>>> with open(r"C:\Users\me\Downloads\xl_resp.xlsx", "wb") as file_writer:
for chunk in xl_resp.iter_content(1024):
file_writer.write(chunk)
1024
1024
...
1024
471
>>> with blob.open("wb") as blob_writer:
for chunk in resp.iter_content(1024):
blob_writer.write(chunk)
1024
1024
...
1024
471
如何防止这种行为?
【问题讨论】:
-
您是否在 IDE 提供的交互式解释器中运行这些代码片段?因为这看起来像是来自
write调用的返回值,它们是由过度热情的 REPL 打印的,而不是来自iter_content本身的任何内容。我不认为普通的 REPL 会这样做(循环中的表达式语句的返回值被忽略,只打印顶级表达式语句的结果)。 -
啊,有道理!是的,这是来自与 python 安装一起打包的 IDLE。在决定如何实现一些逻辑之前,我只是在运行一些测试。
标签: python python-3.x python-requests