Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with 401 (unauthorised) in python requests

What I want to do is GET from a site and if that request returns a 401, then redo my authentication wiggle (which may be out of date) and try again. But I don't want to try a third time, since that would be my authentication wiggle having the wrong credentials. Does anyone have a nice way of doing this that doesn't involve properly ugly code, ideally in python requests library, but I don't mind changing.

like image 886
David Boshton Avatar asked Dec 19 '22 10:12

David Boshton


1 Answers

It doesn't get any less ugly than this, I think:

import requests
from requests.auth import HTTPBasicAuth

response = requests.get('http://your_url')

if response.status_code == 401:    
    response = requests.get('http://your_url', auth=HTTPBasicAuth('user', 'pass'))

if response.status_code != 200:
    # Definitely something's wrong
like image 99
José Tomás Tocino Avatar answered Dec 28 '22 07:12

José Tomás Tocino