[英]Python Requests payload format
I am working on a POST request using requests library. 我正在使用请求库处理POST请求。
My post requests is working fine if I am using carriage returns in my payload, such as this: 如果我在有效负载中使用回车符,则我的帖子请求工作正常,例如:
payload = "{\r\n \"name\": \r\n {\r\n \"@action\": \"login\",\r\n \"@appname\": \"app\",\r\n \"@class\": \"login\",\r\n \"@nocookie\": 1,\r\n \"@code\": \"101\",\r\n \"@psw\": \"12345\",\r\n \"@relogin\": \"0\",\r\n \"@username\": \"user123\"\r\n }\r\n}\r\n"
But if I format it to make the payload look pretty the request is not working: 但是,如果我格式化它以使有效负载看起来很漂亮,则该请求将无法正常工作:
payload = {
'name':
{
'@action': "login",
'@appname': "app",
'@class': "login",
'nocookie': 1,
'@code': "101",
'psw': "12345",
'@relogin': "0",
'@username': "user123"
}
}
I am getting 500 Error using the second payload. 使用第二个有效负载时出现500错误。 First payload works as expected.
第一个有效负载按预期工作。 Any ideas?
有任何想法吗?
Most likely, you just need to create a JSON string from your structure using the function json.dumps
first: 最有可能的是,您只需要使用
json.dumps
函数从您的结构中创建一个JSON字符串:
data = json.dumps(payload)
And then use the data
variable instead of your original payload
. 然后使用
data
变量代替原始的payload
。
From the documentation for requests
: 从文档的
requests
:
For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data:
例如,GitHub API v3接受JSON编码的POST / PATCH数据:
>>> import json >>> url = 'https://api.github.com/some/endpoint' >>> payload = {'some': 'data'} >>> r = requests.post(url, data=json.dumps(payload))
Instead of encoding the dict yourself, you can also pass it directly using the json parameter (added in version 2.4.2) and it will be encoded automatically:
除了自己编码dict外,您还可以使用json参数(在2.4.2版中添加)直接传递dict,它将自动进行编码:
>>> url = 'https://api.github.com/some/endpoint' >>> payload = {'some': 'data'} >>> r = requests.post(url, json=payload)
If you have a dictionary, and the API accepts JSON, you can just pass json=payload
. 如果您有字典,并且API接受JSON,则只需传递
json=payload
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.