使用Python urllib2的个人访问令牌访问Github API

时间:2014-05-14 16:03:46

标签: python api github authorization urllib2

我正在访问Github API v3,它工作正常,直到我达到速率限制,所以我从Github设置页面创建了一个个人访问令牌。我正在尝试使用带有urllib2的令牌和以下代码:

from urllib2 import urlopen, Request

url = "https://api.github.com/users/vhf/repos"
token = "my_personal_access_token"
headers = {'Authorization:': 'token %s' % token}
#headers = {}

request = Request(url, headers=headers)
response = urlopen(request)
print(response.read())

如果我取消注释注释行(直到我达到每小时60个请求的速率限制),此代码才能正常工作。但是当我运行代码时,我得到了urllib2.HTTPError: HTTP Error 401: Unauthorized

我做错了什么?

2 个答案:

答案 0 :(得分:27)

我不知道为什么这个问题被记下来了。无论如何,我找到了答案:

from urllib2 import urlopen, Request
url = "https://api.github.com/users/vhf/repos"
token = "my_personal_access_token"

request = Request(url)
request.add_header('Authorization', 'token %s' % token)
response = urlopen(request)
print(response.read())

答案 1 :(得分:9)

我意识到这个问题已有几年了,但如果有人想使用个人访问令牌同时使用requests.getrequests.post方法,您也可以选择使用以下方法:

request.get(url, data=data, auth=('user','{personal access token}')) 

这只是基本身份验证as documented in the requests library,显然您可以将个人访问令牌传递给according to the github api docs.

来自文档:

  

通过OAuth令牌或者,您可以使用个人访问令牌或    OAuth令牌代替您的密码。

     

curl -u username:token https://api.github.com/user

     

这种方法是   如果您的工具仅支持基本身份验证,则非常有用   利用OAuth访问令牌安全功能。

相关问题