Alex Zel
Alex Zel

Reputation: 688

Test requests authentication

i have this function that downloads files from our companies repository, everything works fine, the problem is that when an incorrect username or password in inserted it doesn't notify me of that, it just downloads a 0 KB file and fails when it tries to extract it. Is there any way i can make sure that the password/username is correct? or at least know that when an error happens that it's because of that?

Here's the function, it's part of a larger script with 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

Upvotes: 1

Views: 139

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123022

You need to validate that you got a 200 OK response before downloading. If the wrong username or password was sent, the server will probably respond with a 403 (Forbidden) or 401 (Unauthorized) status code instead.

You can check the Response.status_code attribute:

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

or you can explicitly test for 40x codes:

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

or you can ask the response object to raise an exception if the response code is not a successful one, by calling the Response.raise_for_status() method:

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

See Response Status Codes in the Quickstart documentation.

Upvotes: 2

Related Questions