如何在python中创建与这个curl调用等价的函数?

2024-05-29 04:48:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我面临以下代码问题:

!curl -X POST \
      -H 'Content-Type':'application/json' \
      -d '{"data":[[4]]}' \
      http://0.0.0.0/score

如何将此代码转换为Python函数或使用Postman?你知道吗


Tags: 函数代码jsonhttpdataapplicationtypecontent
2条回答
import requests

payload = {
    "data": [[4]]
}

headers = {
    'Content-Type': "application/json",
}

server_url = 'http://0.0.0.0/score'

requests.post(server_url, json = payload, headers = headers)

应该大致相当于curl命令。你知道吗

否则,要将curl“翻译”成Python命令,可以使用https://curl.trillworks.com/#python之类的工具。你知道吗

Postman有一个方便的"import" tool来导入curl像您这样的命令(将您的命令粘贴为原始文本)。
结果也可以使用Postman "exported" into Python code。你知道吗

最短等价物(带requestslib)如下所示:

import requests  # pip install requests
r = requests.post("http://0.0.0.0/score", json={"data":[[4]]})

requests将自动为此请求设置适当的Content-Type头。你知道吗


注意,在请求头中仍然会有一些差异,因为curlrequests总是隐式地设置它们自己的头集。你知道吗

您的curl命令将发送这组标头:

"Accept": "*/*",
"Content-Length": "8",  # not the actual content length
"Content-Type": "application/json",
"Host": "httpbin.org",  # for testing purposes
"User-Agent": "curl/7.47.0"

requests头将如下所示:

"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.22.0",
"Content-Length": "8",
"Accept": "*/*",
"Content-Type": "application/json"

因此,如果需要,您可以在headers=关键字参数中手动指定User-Agent头。
但仍将使用压缩。你知道吗

相关问题 更多 >

    热门问题