测试请求身份验证

时间:2015-06-08 09:15:50

标签: python python-3.x

我有这个从我们的公司存储库下载文件的功能,一切正常,问题是当插入的用户名或密码不正确时,它不会通知我,它只是下载一个0 KB文件并在它试图提取它。 有什么方法可以确保密码/用户名是正确的吗?或者至少知道发生错误时是因为那个?

这是函数,它是使用tkinter GUI的更大脚本的一部分。

def download_file(dl_url, local_save_path):
    dnl_sum = 1024
    local_filename = dl_url.split('/')[-1]
    complete_name = os.path.join(local_save_path, local_filename)
    # Get file size
    r = requests.head(dl_url, auth=(username.get(), password.get()), verify=False)
    try:
        dl_file_size = int(r.headers['content-length'])
        file_size.set(str(int(int(r.headers['content-length']) * (10 ** -6))) + "MB")
        c = 1
    except KeyError:
        c = 0
        pass
    r = requests.get(dl_url, stream=True, auth=(username.get(), password.get()), verify=False)
    while True:
        try:
            with open(complete_name, 'wb') as f:
                for chunk in r.iter_content(chunk_size=1024):
                    if chunk:  # filter out keep-alive new chunks
                        f.write(chunk)
                        f.flush()
                        if c == 1:
                            download_perc.set(percentage(dl_file_size, dnl_sum))
                        elif c == 0:
                            print(dnl_sum)
                        dnl_sum = os.path.getsize(complete_name)
        except FileNotFoundError:
            continue
        break

1 个答案:

答案 0 :(得分:2)

您需要在下载前验证您是否收到了200 OK响应。如果发送了错误的用户名或密码,服务器可能会回复403(禁止)或401(未授权)状态代码。

您可以查看Response.status_code attribute

if r.status_code == 200:
    # successful, download response to a file

或者您可以明确测试40x代码:

if r.status_code in (401, 403):
    # access denied, handle this and don't download

或者,如果响应代码不成功,可以通过调用Response.raise_for_status() method来询问响应对象引发异常:

r.raise_for_status()  # raises exception if a 4xx or 5xx status was returned

请参阅快速入门文档中的Response Status Codes

相关问题