下载流响应的实用工具¶
- requests_toolbelt.downloadutils.stream.stream_response_to_file(response, path=None, chunksize=512)¶
将响应主体流式传输到指定的文件。
使用提供的
path
或使用Content-Disposition
头中提供的名称。警告
如果您将此函数作为
path
参数传递给打开的文件类似对象,则该函数不会为您关闭该文件。警告
此函数不会自动关闭作为
response
参数传递的响应对象。如果
path
参数是一个目录,则此函数将解析响应上的Content-Disposition
头,以确定服务器报告的文件名称,并返回指定目录中的文件路径。如果没有提供path
参数,则此函数将默认为进程的当前工作目录。import requests from requests_toolbelt import exceptions from requests_toolbelt.downloadutils import stream r = requests.get(url, stream=True) try: filename = stream.stream_response_to_file(r) except exceptions.StreamingError as e: # The toolbelt could not find the filename in the # Content-Disposition print(e.message)
您还可以将文件名指定为字符串。这将传递给内置
open()
,我们将读取内容到文件中。import requests from requests_toolbelt.downloadutils import stream r = requests.get(url, stream=True) filename = stream.stream_response_to_file(r, path='myfile')
如果计算出的下载文件路径已存在,则此函数将引发 StreamingError。
相反,如果您想自己管理文件对象,则需要提供
io.BytesIO
对象或使用 ‘b’ 标志打开的文件。有关更多详细信息,请参阅以下两个示例。import requests from requests_toolbelt.downloadutils import stream with open('myfile', 'wb') as fd: r = requests.get(url, stream=True) filename = stream.stream_response_to_file(r, path=fd) print('{} saved to {}'.format(url, filename))
import io import requests from requests_toolbelt.downloadutils import stream b = io.BytesIO() r = requests.get(url, stream=True) filename = stream.stream_response_to_file(r, path=b) assert filename is None
- 参数:
- 返回:
如果可以确定,则为文件名,否则为 None
- 返回类型:
- 引发:
- requests_toolbelt.downloadutils.tee.tee(response, fileobject, chunksize=65536, decode_content=None)¶
将响应流式传输到生成器和文件。
这将流式传输响应主体,同时将字节写入
fileobject
。示例用法
resp = requests.get(url, stream=True) with open('save_file', 'wb') as save_file: for chunk in tee(resp, save_file): # do stuff with chunk
import io resp = requests.get(url, stream=True) fileobject = io.BytesIO() for chunk in tee(resp, fileobject): # do stuff with chunk
- 参数:
response (requests.Response) – 来自 requests 的响应。
fileobject (file, io.BytesIO) – 可写的类文件对象。
chunksize (int) – (可选),尝试流式传输的块大小。
decode_content (bool) – (可选),如果为 True,这将解码响应的压缩内容。
- 引发:
如果 fileobject 未使用正确的模式打开或不是 BytesIO 对象,则会引发 TypeError。
- requests_toolbelt.downloadutils.tee.tee_to_bytearray(response, bytearr, chunksize=65536, decode_content=None)¶
将响应流式传输到生成器和字节数组。
这将流式传输提供给函数的响应,将它们添加到提供的
bytearray
中,并将其生成给用户。注意
默认情况下,这使用
bytearray.extend()
,而不是将字节数组传递到readinto
方法中。示例用法
b = bytearray() resp = requests.get(url, stream=True) for chunk in tee_to_bytearray(resp, b): # do stuff with chunk
- requests_toolbelt.downloadutils.tee.tee_to_file(response, filename, chunksize=65536, decode_content=None)¶
将响应流式传输到生成器和文件。
这将打开名为
filename
的文件,并在将字节写入打开的文件对象时流式传输响应正文。示例用法
resp = requests.get(url, stream=True) for chunk in tee_to_file(resp, 'save_file'): # do stuff with chunk