python3 github authorizaitons Oauth2无法正常工作

时间:2012-04-09 20:34:09

标签: python-3.x oauth-2.0 urllib github-api

我正在尝试在Python3中实现oauth2客户端,以便我可以将文件上传到github。对于一个非常基本的开始,我正在尝试使用API获取授权列表。

此代码有效:

from subprocess import Popen,PIPE
user = 'MYUSERNAME'
pw   = 'MYPASSWORD'
git_url = "https://api.github.com/authorizations"
res = Popen(['curl','--user',user + ':' + pw,git_url],stdout=PIPE,stderr=PIPE).communicate()[0]
print(res)

此代码不起作用:

user = 'MYUSERNAME'
pw   = 'MYPASSWORD'
git_url = "https://api.github.com/authorizations"
import urllib.request
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm=None,
                          uri=git_url,
                          user=user,
                          passwd=pw)
opener = urllib.request.build_opener(auth_handler)
f = opener.open(git_url)
print(f.read())

实际上,它会产生此错误:

Traceback (most recent call last):
  File "demo.py", line 18, in <module>
    f = opener.open("https://api.github.com/authorizations")
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/urllib/request.py", line 375, in open
    response = meth(req, response)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/urllib/request.py", line 487, in http_response
    'http', request, response, code, msg, hdrs)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/urllib/request.py", line 413, in error
    return self._call_chain(*args)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/urllib/request.py", line 347, in _call_chain
    result = func(*args)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/urllib/request.py", line 495, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found

我知道python中有一个现有的Oauth2实现,但它是python2,而不是python3,并且它比我需要的更多。

我也知道我可以让我的Python程序调用{​​{1}},这就是我的后备。

我真的很想知道我做错了什么。

感谢。

1 个答案:

答案 0 :(得分:1)

我刚才posted an answer to another question使用了来自python2的urllib2的完整示例。显然你对python3感兴趣,但不应该很难迁移代码。

希望有所帮助,