Skip to main content
 首页 » 编程设计

python之添加多个身份验证处理程序以请求调用

2025年02月15日9shanyou

在 urllib.requests 中,您可以构建开启器,您可以在其中传递多个身份验证处理程序。你能用 Python 请求做同样的事情吗?

请求文档站点上的示例显示一次只传递一个身份验证处理程序,但我需要传递两个。这可能吗?

有人可以提供有关如何执行此操作的语法/文档吗?

这是我在 urllib.requests 包中的做法:

password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() 
 
# Add the username and password. 
# If we knew the realm, we could use it instead of None. 
top_level_url = "http://example.com/foo/" 
password_mgr.add_password(None, top_level_url, username, password) 
 
handler1 = urllib.request.HTTPBasicAuthHandler(password_mgr) 
handler2 = urllib.request.HTTPDigestAuthHandler(password_mgr) 
# create "opener" (OpenerDirector instance) 
opener = urllib.request.build_opener([handler1, handler2]) 
 
# use the opener to fetch a URL 
opener.open(a_url) 
 
# Install the opener. 
# Now all calls to urllib.request.urlopen use our opener. 
urllib.request.install_opener(opener) 

请您参考如下方法:

看来 Requests 不支持这个。我在 github Issue 页面上发布了这个问题。建议使用:http://toolbelt.readthedocs.io/en/latest/authentication.html#guessauth

我还没有尝试过,但它似乎是一个可行的解决方案。