Abh*_*and 4 python api urlencode heroku flask
我正在尝试将生产就绪代码部署到Heroku进行测试。不幸的是,它没有获取JSON数据,因此我们将其转换为x-www-form-urlencoded。
params = urllib.parse.quote_plus(json.dumps({
'grant_type': 'X',
'username': 'Y',
'password': 'Z'
}))
r = requests.post(URL, data=params)
print(params)
Run Code Online (Sandbox Code Playgroud)
由于我猜测data=params格式不正确,因此该行显示错误。
有什么方法可以将urlencoded参数发布到API?
您无需显式编码,只需传递一个dict。
>>> r = requests.post(URL, data = {'key':'value'})
Run Code Online (Sandbox Code Playgroud)
从文档中:
通常,您希望发送一些表单编码的数据,就像HTML表单一样。为此,只需将字典传递给data参数。提出请求后,您的数据字典将自动进行表单编码
需要注意的重要一点是,对于嵌套 json 数据,您需要将嵌套 json 对象转换为字符串。
data = { 'key1': 'value',
'key2': {
'nested_key1': 'nested_value1',
'nested_key2': 123
}
}
Run Code Online (Sandbox Code Playgroud)
字典需要转换成这种格式
inner_dictionary = {
'nested_key1': 'nested_value1',
'nested_key2': 123
}
data = { 'key1': 'value',
'key2': json.dumps(inner_dictionary)
}
r = requests.post(URL, data = data)
Run Code Online (Sandbox Code Playgroud)
小智 6
将Content-Type标题设置为application/x-www-form-urlencoded.
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
r = requests.post(URL, data=params, headers=headers)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6701 次 |
| 最近记录: |