我有一个网址,我可以针对
发出curl请求curl --insecure --header "Expect:" \
--header "Authorization: Bearer <api key>" \
https://some-url --silent --show-error --fail -o data-package.tar -v
我在这里尝试使用请求模块
r = requests.get('https://stg-app.conduce.com/conduce/api/v1/admin/export/' + id,
headers=headers)
r.content ##binary tar file info
如何将其写入类似tarfile的数据包?
答案 0 :(得分:1)
content
将是您可以写出的整个文件(以字节为单位)。
import requests
r = requests.get('...YOUR URL...')
# Create a file to write to in binary mode and just write out
# the entire contents at once.
# Also check to see if we get a successful response (add whatever codes
# are necessary if this endpoint will return something other than 200 for success)
if r.status_code in (200,):
with open('tarfile.tar', 'wb') as tarfile:
tarfile.write(r.content)
如果您正在下载任意tar文件并且它可能相当大,您可以choose to stream it代替。
import requests
tar_url = 'YOUR TAR URL HERE'
rsp = requests.get(tar_url, stream=True)
if rsp.status_code in (200,):
with open('tarfile.tar', 'wb') as tarfile:
# chunk size is how many bytes to read at a time,
# feel free to adjust up or down as you see fit.
for file_chunk in rsp.iter_content(chunk_size=512):
tarfile.write(chunk)
请注意,此模式(使用wb
模式打开文件)通常应该与编写任何类型的二进制文件一起使用。我建议阅读writing file documentation for Python 3(Python 2 documentation here)。