gpt4 book ai didi

python - 使用 Python 的 HTTPBasicAuthHandler 进行 Bitbucket API 身份验证

转载 作者:太空宇宙 更新时间:2023-11-03 13:05:58 24 4
gpt4 key购买 nike

我正在尝试使用 bitbucket's API 获取私有(private)存储库中的问题列表.

我已确认 HTTP 基本身份验证适用于 hurl ,但我无法在 Python 中进行身份验证。改编此 tutorial 中的代码, 我写了下面的脚本。

import cookielib
import urllib2

class 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.62
Date: Mon, 19 Apr 2010 16:15:06 GMT
Content-Type: text/plain
Connection: close
Vary: Authorization,Cookie
Content-Length: 9

Traceback (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 e
HTTPError: 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 - 使用 Python 的 HTTPBasicAuthHandler 进行 Bitbucket API 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2669147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com