什么是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它.通常,您不会关心身份验证的领域,只关心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)
将用户名和密码设置为以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')