代码之家  ›  专栏  ›  技术社区  ›  Saqib Ali

如何将这个Curl命令转换成Pycurl调用?

  •  1
  • Saqib Ali  · 技术社区  · 6 年前

    我正在运行下面的curl命令,我从Unix命令行运行它来执行googleoauth,它运行得非常好。我得到一个包含访问令牌的响应。

    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 回复  |  直到 6 年前
        1
  •  1
  •   halfer    4 年前

    这次修改怎么样?

    发件人:

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

    收件人:

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

    注:

    • import urllib .
    推荐文章