本文介绍了使用Python的HTTPBasicAuthHandler进行Bitbucket API身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我正在尝试使用 bitbucket的API 获取私有存储库中的问题列表。 / a>。I'm trying to get the list of issues on a private repository using bitbucket's API.我已经确认HTTP基本身份验证可与 hurl ,但是我无法在Python中进行身份验证。从教程改编代码后,我编写了以下脚本。I have confirmed that HTTP Basic authentication works with hurl, but I am unable to authenticate in Python. Adapting the code from this tutorial, I have written the following script.import cookielibimport urllib2class API(): api_url = 'http://api.bitbucket.org/1.0/' def __init__(self, username, password): self._opener = self._create_opener(username, password) def _create_opener(self, username, password): cj = cookielib.LWPCookieJar() cookie_handler = urllib2.HTTPCookieProcessor(cj) password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() password_manager.add_password(None, self.api_url, username, password) auth_handler = urllib2.HTTPBasicAuthHandler(password_manager) opener = urllib2.build_opener(cookie_handler, auth_handler) return opener def get_issues(self, username, repository): query_url = self.api_url + 'repositories/%s/%s/issues/' % (username, repository) try: handler = self._opener.open(query_url) except urllib2.HTTPError, e: print e.headers raise e return handler.read()api = API(username='my_username', password='XXXXXXXX') api.get_issues('my_username',' my_repository')会导致:>>>Server: nginx/0.7.62Date: Mon, 19 Apr 2010 16:15:06 GMTContent-Type: text/plainConnection: closeVary: Authorization,CookieContent-Length: 9Traceback (most recent call last): File "C:/USERS/personal/bitbucket-burndown/bitbucket-api.py", line 29, in <module> print api.get_issues('my_username', 'my_repository') File "C:/USERS/personal/bitbucket-burndown/bitbucket-api.py", line 25, in get_issues raise eHTTPError: HTTP Error 401: UNAUTHORIZED api。 get_issues('jespern','bitbucket')就像一种魅力。我的代码有什么问题?推荐答案 HTTPBasicAuthHandler 。这有效:class API(): api_url = 'http://api.bitbucket.org/1.0/' def __init__(self, username, password, proxy=None): encodedstring = base64.encodestring("%s:%s" % (username, password))[:-1] self._auth = "Basic %s" % encodedstring self._opener = self._create_opener(proxy) def _create_opener(self, proxy=None): cj = cookielib.LWPCookieJar() cookie_handler = urllib2.HTTPCookieProcessor(cj) if proxy: proxy_handler = urllib2.ProxyHandler(proxy) opener = urllib2.build_opener(cookie_handler, proxy_handler) else: opener = urllib2.build_opener(cookie_handler) return opener def get_issues(self, username, repository): query_url = self.api_url + 'repositories/%s/%s/issues/' % (username, repository) try: req = urllib2.Request(query_url, None, {"Authorization": self._auth }) handler = self._opener.open(req) except urllib2.HTTPError, e: print e.headers raise e return json.load(handler) 这篇关于使用Python的HTTPBasicAuthHandler进行Bitbucket API身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!