Python 使用请求模块下载文件会创建一个空文件

Python 使用请求模块下载文件会创建一个空文件,python,python-requests,Python,Python Requests,经过几次尝试,在这里看到了很多示例和问题,我不明白为什么我不能使用请求模块下载文件,我尝试下载的文件大约只有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=10

经过几次尝试,在这里看到了很多示例和问题,我不明白为什么我不能使用请求模块下载文件,我尝试下载的文件大约只有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进行身份验证,该信息在规范中不可用。上面的代码工作正常。我投票决定结束这个问题。

从答案中尝试以下内容

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)

我在这里为我的问题添加解决方案,以防有人需要:

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

看到这个了吗?你能从浏览器下载这个文件而不出任何问题吗?另外,检查响应头也不会有什么坏处。@Himal我刚刚发现,为了使用api下载文件,我必须启动一个具有身份验证的会话。我将打开另一个问题并更新此问题。我将投票结束此问题,因为代码是有效的,是客户给出的一个说明错误导致我出错。