Python中的HTTP认证

2024-04-26 14:36:26 发布

您现在位置:Python中文网/ 问答频道 /正文

Whats是python urllib的等价物

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

我做到了:

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

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


Tags: comjsonhttpexamplestatususernameupdatepassword
2条回答

诀窍是创建一个密码管理器,然后告诉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)

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

http://www.voidspace.org.uk/python/articles/urllib2.shtml#id6可以找到一个很好的文档来描述这一点。

是的,看看urllib2.HTTP*AuthHandlers

文档中的示例:

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')

相关问题 更多 >