Я запускаю следующую команду curl, которую я запускаю из командной строки Unix для выполнения Google OAuth, и она прекрасно работает. Я получил ответ, содержащий токен доступа.
curl \
--request POST \
--header "Cache-Control: no-cache" \
--header "Content-Type: application/x-www-form-urlencoded" \
--data 'code=my-first-magic-code&client_id=my-magic-client-id&grant_type=authorization_code&client_secret=my-magic-client-secret&redirect_uri=http://www.my-magic-website.com/google-login-callback' \
"https://accounts.google.com/o/oauth2/token"
Ответ (200):
{
"access_token": "ya29.Glwb-blah-blah-blah-pjKiA",
"expires_in": 3575,
"scope": "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",
"token_type": "Bearer",
"id_token": "eyJhb-blah-blah-blah-Xjz4g"
}
Как я могу написать эквивалентную команду, используя pyCurl? Ниже то, что я написал:
#!/usr/bin/env python
import pycurl
from StringIO import StringIO
import httplib
import json
response_buffer = StringIO()
c = pycurl.Curl()
c.setopt(c.URL, 'https://accounts.google.com/o/oauth2/token')
c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded',
'Cache-Control: no-cache'])
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, json.dumps({
'code': raw_input('Enter the new Auth Code you got from the web here: '),
'client_id': 'my-magic-client-id',
'client_secret': 'my-magic-client-secret',
'grant_type': 'authorization_code',
'redirect_uri': 'http://www.my-magic-website.com/google-login-callback'
}))
c.setopt(c.WRITEDATA, response_buffer)
c.perform()
if c.getinfo(pycurl.HTTP_CODE) == httplib.OK:
print 'Worked! {}'.format(json.loads(response_buffer.getvalue()))
else:
print 'Failed! {}'.format(json.loads(response_buffer.getvalue()))
Однако, когда я запускаю эту программу, она перестает работать следующим образом:
Enter the new Auth Code you got from the web here: my-second-magic-code
Failed! {u'error_description': u'Invalid grant_type: ', u'error': u'unsupported_grant_type'}