python-3.x - 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 2 和 3 检查 RingCentral,您可以在此处逐步学习使用 Python 原生 API 访问 RingCentral 服务:
https ://ringcentral-tutorials.github.io/call-ringcentral-apis-native- python-demo/?distinctId=171e1c5b614e8-078e90c97b438a-1d346655-fa000-171e1c5b615fa#0
您可以找到它如何访问状态代码、定义和处理令牌以及处理授权
推荐阅读
- c# - 如何获取每个月底的最后一行
- swift - 从 Swift 处理 FSEventStreamRef API 中的选项
- ethereum - 使用 Web3 调用智能合约函数
- python - PyQt5 - QPushButton.pressed() 信号/插槽未更新 QLabel 小部件
- spring - 他们是否有任何替代方法可以将资源过滤与 Maven 一起用于 Spring Boot 应用程序?
- scheduler - 在谷歌云 sql 中调度函数 - Postgresql DB
- python-3.x - 数据和 X 轴标签不对齐
- ios - 如何将我的类对象转换为 JSON for Alamofire
- ms-word - 如何定义自定义高亮颜色?
- angular - 如何在 firestore 和 ionic 4 中使用 snapshotChanges()