问题
After a few tentatives and seeing a lot of examples and questions around here I can't figure out why I'm not able to download a file using requests module, the File i'm trying to download is around 10mb only:
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
Empty file:
[xxx@xxx ~]$ ls -ltra /tmp/aaaaaa
-rw-rw-r--. 1 xxx xxx 0 Jul 21 12:38 /tmp/aaaaaa
EDIT: I just discovered that it's necessary to authenticate into the API with session instead basic authentication, that information wasn't available on the specification. The code above works properly. I voted to close this question.
回答1:
From the answers here try something like
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)
回答2:
I'm adding the solution to my problem here, in case that anyone needs it:
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
来源:https://stackoverflow.com/questions/45236801/downloading-file-using-requests-module-creates-an-empty-file