HTTP Authentication in Python(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)
有没有更好/更简单的方法?
Is there a better / simpler way?
推荐答案
诀窍是创建一个密码管理器,然后告诉 urllib.通常,您不会关心身份验证的领域,只关心主机/网址部分.例如:
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 开头的 URL 设置用户名和密码.其他选项是在此处指定主机名或更完整的 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.
这篇关于Python 中的 HTTP 身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python 中的 HTTP 身份验证
基础教程推荐
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
