gpt4 book ai didi

python - 在下载期间使用 Requests.response 从文件中读取数据

转载 作者:太空宇宙 更新时间:2023-11-04 00:24:08 25 4
gpt4 key购买 nike

对于上下文:我的代码的以下版本可以很好地将整个图像文件下载+写入磁盘,而无需在写入之前从中读取任何数据。

response = requests.get(url, stream=True)
if response.status_code == 200:
with open(filename, 'wb') as outfile:
for chunk in response.iter_content(chunk_size=256):
outfile.write(chunk)
outfile.close()

我在读取第一个 block (包含文件本身的 header ——而不是 http 响应,不需要它)时的失败尝试失败了。

with open(filename, 'wb') as outfile:
chunk1 = response.iter_content(chunk_size=256)

# This gives: '<generator object Response.iter_content.<locals>.generate at 0x033E57E0>'
print(chunk1)

# This fails with error: 'TypeError: a bytes-like object is required, not 'generator'
outfile.write(chunk1)

# Doesn't get to here anymore
for chunk in response.iter_content(chunk_size=256):
outfile.write(chunk)
outfile.close()

我现在很困惑。我不明白为什么 chunk1 拒绝编写,而我的第一个版本代码中 for 循环中的所有 block 都编写得很好。是 print(chunk1) 语句以某种方式改变了 chunk1 吗?

我对迭代器的使用不正确吗?

我也不知道如何查看 chunk1 可能具有哪些包含数据的属性...

我也试过

print(response.content)
print(response.raw.data)
# No good: these both download the entire image file, THEN print it to console.
# But they at least print the data itself instead of giving an object

在下载所有内容之前访问 header 的目的是,如果 header 显示图像出于任何原因不受欢迎,则完全停止下载。所以我认为我必须以某种方式读取使用 iter_contents 检索到的 block 。

但是我该怎么做呢?

最佳答案

您的困惑在于生成器的使用。你不能保存 chunk1,你想使用 next 从生成器中获取下一 block 喜欢:

代码:

outfile.write(next(chunk1))

完整代码:

import requests

url = 'https://raw.githubusercontent.com/mattupstate/flask-mail/master/flask_mail.py'
filename = 'flask_mail.py'

response = requests.get(url, stream=True)
if response.status_code == 200:

with open(filename, 'wb') as outfile:

# get the next chunk and save to disk
outfile.write(next(response.iter_content(chunk_size=256)))

for chunk in response.iter_content(chunk_size=256):
outfile.write(chunk)

请注意,当您使用上下文管理器(with open(...)时,您不需要close

关于python - 在下载期间使用 Requests.response 从文件中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48038986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com