Python 中的 HTTP 身份验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/720867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:43:53  来源:igfitidea点击:

HTTP Authentication in Python

authenticationcurlhttp-headerspython

提问by Lakshman Prasad

Whats is the python urllib equivallent of

什么是 python urllib 等价物

curl -u username:password status="abcd" http://example.com/update.json

I did this:

我这样做了:

handle = urllib2.Request(url)
authheader =  "Basic %s" % base64.encodestring('%s:%s' % (username, password))
handle.add_header("Authorization", authheader)

Is there a better / simpler way?

有没有更好/更简单的方法?

回答by Ivo

The trick is to create a password manager, and then tell urllib about it. Usually, you won't care about the realm of the authentication, just the host/url part. For example, the following:

诀窍是创建一个密码管理器,然后告诉 urllib。通常,您不会关心身份验证的领域,只关心主机/url 部分。例如,以下内容:

password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
top_level_url = "http://example.com/"
password_mgr.add_password(None, top_level_url, 'user', 'password')
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(urllib2.HTTPHandler, handler)
request = urllib2.Request(url)

Will set the user name and password to every URL starting with top_level_url. Other options are to specify a host name or more complete URL here.

将用户名和密码设置为每个以top_level_url. 其他选项是在此处指定主机名或更完整的 URL。

A good document describing this and more is at http://www.voidspace.org.uk/python/articles/urllib2.shtml#id6.

http://www.voidspace.org.uk/python/articles/urllib2.shtml#id6 上有一个很好的文档来描述这一点以及更多内容。

回答by Lakshman Prasad

Yes, have a look at the urllib2.HTTP*AuthHandlers.

是的,看看urllib2.HTTP*AuthHandlers

Example from the documentation:

文档中的示例:

import urllib2
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
                          uri='https://mahler:8092/site-updates.py',
                          user='klem',
                          passwd='kadidd!ehopper')
opener = urllib2.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib2.install_opener(opener)
urllib2.urlopen('http://www.example.com/login.html')