Python中的HTTP身份验证 [英] HTTP Authentication in Python

查看:329
本文介绍了Python中的HTTP身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是python urllib等价的

Whats is the python urllib equivallent of

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)

有更好/更简单方法?

推荐答案

诀窍是创建一个密码管理器,然后告诉urllib。通常,你不会在乎认证的领域,只是host / url部分。例如,以下内容:

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:

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 开头。其他选项是在此处指定主机名或更完整的网址。

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.

一个很好的文档描述这个和更多是在 http://www.voidspace.org.uk/python/articles/urllib2.shtml#id6

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

这篇关于Python中的HTTP身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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