经过一些尝试并看到很多示例和问题后,我无法弄清楚为什么我无法使用请求模块下载文件,我试图下载的文件只有10mb左右:
try:
r = requests.get('http://localhost/sample_test', auth=('theuser', 'thepass'), stream=True)
with open('/tmp/aaaaaa', 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
f.write(chunk)
except:
raise
空文件:
[xxx@xxx ~]$ ls -ltra /tmp/aaaaaa
-rw-rw-r--. 1 xxx xxx 0 Jul 21 12:38 /tmp/aaaaaa
编辑:我刚刚发现有必要通过会话而不是基本身份验证对API进行身份验证,该规范中没有该信息。上面的代码工作正常。我投票结束了这个问题。
答案 0 :(得分:3)
从答案here尝试类似
的内容import requests
url = 'http://localhost/sample_test'
filename = '/tmp/aaaaaa'
r = requests.get(url, auth=('theuser', 'thepass'), stream=True)
if r.status_code == 200:
with open(filename, 'wb') as f:
f.write(r.content)
答案 1 :(得分:0)
我在这里为我的问题添加解决方案,万一有人需要它:
import requests
auth = 'http://localhost/api/login'
payload = {'username': 'the_user', 'password': 'the_password'}
with requests.Session() as session:
r = session.post(auth, data=payload)
if r.status_code == 200:
print('downloading')
get = session.get('http://localhost/sample_test', stream=True)
if get.status_code == 200:
with open('/tmp/aaaaaa', 'wb') as f:
for chunk in get.iter_content(chunk_size=1024):
f.write(chunk)
else:
print r.status_code