authentication - Python 中的 HTTP 身份验证

标签 authentication curl http-headers python

什么是 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)

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

最佳答案

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

关于authentication - Python 中的 HTTP 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/720867/

相关文章:

客户端的 Azure KeyVault 和身份验证

php - CodeIgniter 身份验证 + 用户权限

javascript - 有没有办法检查用户是否使用express.Router中间件登录?

authentication - OpenWrt:LuCI:如何实现受限用户访问

php - 使用带有 curl php 示例的 VBA 将 HTTP 发布到 Web 服务

php - PHP重定向503而不更改URL

perl - 在 Windows 上为 Perl 安装 cURL 模块

php - 绕过 PHP CURL 2GB 下载限制

http - 是否可以判断 HTTP 请求是否源自 "save link as"操作?

caching - Cache-Control 的无缓存和必须重新验证之间的区别?