【问题标题】:Python requests parameters not going throughPython请求参数不通过
【发布时间】:2016-05-06 01:10:02
【问题描述】:

我正在尝试按照这些说明https://quizlet.com/api/2.0/docs/authorization-code-flow 中的 OAuth 流程向 Quizlet 发出发布请求。我遇到了一个问题,在第 2 步中,我必须使用从他们的服务器生成的令牌发出发布请求,但我没有成功将令牌传递到 url。我知道它是正确生成的,但我在传递它时遇到了问题,并且没有收到 400 响应。

更直接地说,我的问题是,是否有另一种方法来包含我试图通过 post 请求中的 url 传递的 grant_typecode 参数,例如通过标题传递它们发布请求?我查看了requests 的文档,但运气不佳。

@app.route('/')
@app.route('/index')
def index():
    code = request.args.get('code')
    state = request.args.get('state')
    print("code is " + code)
    r = requests.post("https://api.quizlet.com/oauth/token?grant_type=authorization_code&code=" + code)

    return render_template('index.html')

【问题讨论】:

    标签: python flask python-requests


    【解决方案1】:

    您必须指定所需的标头AuthorizationContent-Type

    import requests
    from requests.auth import _basic_auth_str
    
    client_id = 'YOUR CLIENT ID'
    secret = 'YOUR CLIENT SECRET'
    code = 'CODE FROM STEP 1'
    
    headers = {
        'Authorization': _basic_auth_str(client_id, secret),
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    r = requests.post('https://api.quizlet.com/oauth/token?grant_type=authorization_code&code={0}'.format(
        code), headers=headers)
    
    print r.status_code
    print r.content
    

    【讨论】:

    • 好的,我修复了代码中的一个小问题。此外,我将您需要更新的 3 个变量移到了顶部。运行它后,我得到了 200 和一个访问令牌。让我知道它是否适合您。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 2016-07-03
    • 1970-01-01
    相关资源
    最近更新 更多