如何将此 Curl 命令转换为 Pycurl 调用?

How to translate this Curl command into a Pycurl call?

我正在运行使用以下 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'}

这个修改怎么样?

发件人:

c.setopt(pycurl.POSTFIELDS, json.dumps({

收件人:

c.setopt(pycurl.POSTFIELDS, urllib.urlencode({

注:

  • 在这种情况下,还请添加import urllib
  • 在你运行这个脚本之前,请再次检索代码和运行这个脚本。