如何处理python请求中的401(未经授权) [英] How to deal with 401 (unauthorised) in python requests

查看:46
本文介绍了如何处理python请求中的401(未经授权)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是从站点获取 GET,如果该请求返回 401,则重做我的身份验证摆动(可能已过时)并重试.但是我不想第三次尝试,因为那将是我的身份验证摆动具有错误的凭据.有没有人有这样做的好方法,它不涉及适当的丑陋代码,最好是在 python 请求库中,但我不介意改变.

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.

推荐答案

我认为没有比这更丑陋的了:

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

这篇关于如何处理python请求中的401(未经授权)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆