简体   繁体   中英

How do I test for 401 response to a post request in python?

I'm using a post request to access a website that requires authentication. If that authentication is incorrect, I get a Response [401]. I want to test if the authentication is incorrect and if so, abort the process and display an error of some sort. I don't know the syntax to test if the response is 401.

output = requests.post(cfg.get('HTTP', 'url'), data = query, verify=False, auth=HTTPBasicAuth(credentials['user'], credentials['pass']))

        if output == '<Response [401]>':
            sys.exit('Incorrect Authentication. Please try again.')
        else:
            sys.exit('manual stop1')

Instead of '<Response [401]>' , I've also tried 'Response [401]' , 'response [401]' , '<Response[401]>' , 'Response[401]' , 'response[401]' , '[401]' , '401' , and all of those without quotes.

I've seen some responses using flask and json, but I was hoping to not have to change how I'm requesting the data. Thank you!

You want the status_code attribute

if output.status_code == 401:
    ...

Or to avoid hard coding numbers:

if output.status_code == requests.status_codes.codes.UNAUTHORIZED:
    ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM