昨天遇到了一个奇怪的问题,在Python中需要传递dict参数,利用json.dumps将dict转为json格式用post方法发起请求:
1
2
|
params = { "score" :{ "gt" : "80" , "lt" : "90" }} request.post(url, json.dumps(params)) |
但是在服务端接收到的参数日志为:
1
|
Parameters: { "sno" = > "lt" } |
之前用Ruby的RestClient的gem包传递参数还是正常的:
1
2
|
params = { "score" :{ "gt" : "80" , "lt" : "90" }} RestClient.post(url, params.to_json, :content_type => :json) |
服务端接收到的参数日志正确,为:
1
|
Parameters: { "score" = >{ "gt" = > "80" , "lt" = > "90" }} |
仔细观察后发现RestClient中第三个参数为header
百度之后发现应该在Python的request中添加header参数,指明所传的params格式为json,如下:
1
|
requests.post(url, data=json.dumps(params), headers={'Content-Type': 'application/json'}) |
就可以正常在服务端得到传过来的参数了。
到此这篇关于Python中request发送post请求传递json参数的问题的文章就介绍到这了,更多相关Python request发送post请求传递json参数内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/yuanlaidewo000/article/details/80661888