我正在尝试在 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 程序调用curl
,这是我的后备。
我真的很想知道我做错了什么。
谢谢。