首页 > 解决方案 > python 2和python 3中的urlencode方法有区别吗

问题描述

我正在使用 ringCentral 的 API,并尝试使用 python 3 使用密码机制获取身份验证令牌。之前我使用 python 2 完成了它,它仍然可以正常工作。根据 API 文档的要求,我使用 urllib.urlencode() 方法对请求参数进行 URL 编码。python 3中该方法的等效方法是urllib.parse.urlencode(),但是在python 3中执行时我遇到了错误。

{"error": "invalid_request", "errors": [{"errorCode": "OAU-156", "message": 
"Basic authentication header is missing or malformed"}], "error_description": 
"Basic authentication header is missing or malformed"}

我什至在这两种情况下都从 urlencode 方法打印了结果字符串,它是相同的。我不明白这里有什么问题?有什么见解吗?我也找不到带有该错误代码的任何信息。

Python 3 代码:

    import urllib.parse
    import json
    import requests
    basic="%s:%s" % ("<my cllient id>","<my cllient secret>")
    auth_header = {
        "Content-Type": "application/x-www-form-urlencoded",
        "Accept": "application/json",
        "Authorization": "Basic "+ str(base64.b64encode(basic.encode()))
    }
    body = urllib.parse.urlencode({
        'grant_type': 'password',
        'username': "<my number>",
        'password': "<my password>"
    })
    auth_request=requests.request("POST","https://platform.devtest.ringcentral.com/restapi/oauth/token",headers=auth_header,data=body)
    print(json.dumps(auth_request.json()))

Python 2 代码(工作):

    import urllib
    import json
    import requests
    basic="%s:%s" % ("<my cllient id>","<my cllient secret>")
    auth_header = {
        "Content-Type": "application/x-www-form-urlencoded",
        "Accept": "application/json",
        "Authorization": "Basic "+ str(base64.b64encode(basic.encode()))
    }
    body = urllib.urlencode({
        'grant_type': 'password',
        'username': "<my number>",
        'password': "<my password>"
    })
    auth_request=requests.request("POST","https://platform.devtest.ringcentral.com/restapi/oauth/token",headers=auth_header,data=body)
    print(json.dumps(auth_request.json()))

标签: python-3.xpython-2.7urlliburlencoderingcentral

解决方案


您需要将代码放在这里,以便我们解决问题。
同时,请您使用 Python 2 和 3 检查 RingCentral,您可以在此处逐步学习使用 Python 原生 API 访问 RingCentral 服务: https ://ringcentral-tutorials.github.io/call-ringcentral-apis-native- python-demo/?distinctId=171e1c5b614e8-078e90c97b438a-1d346655-fa000-171e1c5b615fa#0

您可以找到它如何访问状态代码、定义和处理令牌以及处理授权


推荐阅读