How to deal with 401 (unauthorised) in python requests

前端 未结 3 597
余生分开走
余生分开走 2021-01-06 05:58

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

3条回答
  •  失恋的感觉
    2021-01-06 06:49

    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
    

提交回复
热议问题