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

时间:2018-09-17 23:40:25

标签: python curl pycurl

我正在运行下面的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'}

1 个答案:

答案 0 :(得分:1)

此修改如何?

发件人:

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

收件人:

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

注意:

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

如果这对您的情况没有帮助,对不起。