Python中的HTTP身份验证

Lak*_*sad 15 python authentication curl http-headers

什么是python urllib等效的

curl -u username:password status="abcd" http://example.com/update.json
Run Code Online (Sandbox Code Playgroud)

我这样做了:

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

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

Ivo*_*Ivo 20

诀窍是创建一个密码管理器,然后告诉urllib它.通常,您不会关心身份验证的领域,只关心host/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)
Run Code Online (Sandbox Code Playgroud)

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

描述这个和更多内容的好文件在http://www.voidspace.org.uk/python/articles/urllib2.shtml#id6.

  • 这比最初的例子更简单? (2认同)

小智 6

是的,看看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')
Run Code Online (Sandbox Code Playgroud)