我正在尝试使用http://developer.github.com/v3/来检索项目问题。这有效:
curl -u "Littlemaple:mypassword" https://api.github.com/repos/MyClient/project/issues
它返回我客户项目的所有私人问题。但是,我无法找到如何在Python中实现它。我找到的两种方式(例如Python urllib2 Basic Auth Problem)都不起作用,它们会返回404或403错误:
def fetch(url, username, password):
"""Wonderful method found on forums which does not work.""""
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPBasicAuthHandler(passman)))
req = urllib2.Request(url)
f = urllib2.urlopen(req)
return f.read()
...和
def fetch(url, username, password):
"""Wonderful method found on forums which does not work neither.""""
request = urllib2.Request(url)
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
return urllib2.urlopen(request).read()
有什么想法吗?提前谢谢!
答案 0 :(得分:9)
r = requests.get('https://api.github.com', auth=('user', 'pass'))
Python请求是这里的方式。我一直在工作和家里广泛使用请求进行各种Web服务交互。与之前相比,使用起来很愉快。注意:auth关键字arg适用于任何需要auth的调用。因此,您可以谨慎使用它,即。每次对github的调用都不需要它,只需要登录。例如:
r = request.get('https://api.github.com/gists/starred, auth=('user', 'pass'))
这里记录了github登录:
答案 1 :(得分:5)
如果是404,您可能只是错误的网址。如果它是403,也许你的领域错了。
对于初学者,您将URL传递给add_password,而实际上您应该只传递基本URL。另外,您应该只创建一个新的开启者,而不是install_opener。
See this recipe for an example:
class NoOpHandler(urllib2.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newUrl):
return None
passmanager = urllib2.HTTPPasswordMgrWithDefaultRealm()
passmanager.add_password(None, baseurl, username, password)
auth_handler = urllib2.HTTPBasicAuthHandler(passmanager)
opener = urllib2.build_opener(auth_handler, NoOpHandler())
答案 2 :(得分:1)
你也可以这样做
r = requests.get('https://user:pass@api.github.com')
答案 3 :(得分:0)