2017-09-01 60 views
0

我有一个网址,我可以卷曲的请求对如何直接将内容写入tar文件?

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 

做我怎样写这一个tar文件,如数据包?

回答

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)。