我想在Python应用程序中使用trakt.tv api进行个人使用,但我无法弄清楚如何处理身份验证。
这是通过OAuth完成的,我正在使用google推荐的回调之一(urn:ietf:wg:oauth:2.0:oob)。从API网站,我应该首先进行授权步骤(我获得一个授权代码),然后将此代码交换为access_token。
我尝试通过从我的浏览器粘贴验证代码来进行交换部分,并且我确实获得了access_token,但是在尝试进行经过身份验证的请求时它仍然提供了403代码。
这是我的代码:
values = """
{
"code": #pasted from browser#,
"client_id": "#client_id#",
"client_secret": "#client_secret#",
"redirect_uri": "urn:ietf:wg:oauth:2.0:oob",
"grant_type": "authorization_code"
}
"""
headers = {
'Content-Type': 'application/json'
}
request = Request('https://api.trakt.tv/oauth/token', data=values, headers=headers)
response_body = json.load(urlopen(request))
token = response_body['access_token'] # token received (checked by print)
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer %s' % token,
'trakt-api-version': '2',
'trakt-api-key': '#client_id#'
}
request = Request('https://api.trakt.tv/sync/watched/movies', headers=headers)
response_body = urlopen(request).read()
print response_body
这会引发以下异常
Traceback (most recent call last):
File "/Users/luisafonsocarvalho/Documents/Auto Downloader/downloader.py", line 81, in <module>
response_body = urlopen(request).read()
File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 410, in open
response = meth(req, response)
File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 448, in error
return self._call_chain(*args)
File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
任何帮助都会非常感激,因为我似乎有点失落。
编辑:
如果我第二次运行该代码,使用相同的值,我会获得401代码。怎么了?