简体   繁体   English

python 与 curl -d 命令的等效请求是什么?

[英]What is the equivalent request of python with curl -d command?

I am having difficulty finding the python request equivalent to the curl command which send the data in the body as JSON.我很难找到与 curl 命令等效的 python 请求,该命令将正文中的数据作为 JSON 发送。

The curl command looks like curl 命令看起来像

curl -X POST -d '{"key1": "value1", "key2": "value2"}' http://localhost:8080/myapi

With the CURL request, Server(python) gets the data in requset.form like below通过 CURL 请求,Server(python) 获取 requset.form 中的数据,如下所示

ImmutableMultiDict([('{"key1": "value1", "key2": "value2"}', '')])

But when sending the same post request like using request module of python但是当像使用python的请求模块一样发送相同的post请求时

response = requests.post("http://localhost:8080/myapi", data=json.dumps({
    "key1": "value1", "key2": "value2"))

From the server-side, I see the content like从服务器端,我看到的内容如下

ImmutableMultiDict([('key1', 'value1'), ('key2', 'value2')]) and its type is : <class 'werkzeug.datastructures.ImmutableMultiDict

I am a bit confused about why the request using requests.post having different content at server side compared to using curl request, can someone please help to understand and possible solutions我对为什么使用 requests.post 的请求与使用 curl 请求相比在服务器端具有不同的内容感到有些困惑,有人可以帮助理解和可能的解决方案


The issue has solved by adding 'Content-Type:application/json' in both curl and the request made from the request module.该问题已通过在 curl 和请求模块发出的请求中添加“Content-Type:application/json”解决。 Also, I used to check the data in request.form but realized that it is working when I use the request.data, new to python so have missed this, thank you.另外,我曾经检查过 request.form 中的数据,但是当我使用 request.data 时意识到它正在工作,python 新手所以错过了这个,谢谢。

Have you tried just sending the dictionary instead of stringified json?您是否尝试过只发送字典而不是字符串化的 json?

r = requests.post('https://httpbin.org/post', data = {"key1": "value1", "key2": "value2"})

running this through the httpbin test server and running your curl statement yield identical responses (with the exception of the user agent.通过 httpbin 测试服务器运行它并运行 curl 语句会产生相同的响应(用户代理除外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM