2024-05-29 04:48:16 发布
网友
我面临以下代码问题:
!curl -X POST \ -H 'Content-Type':'application/json' \ -d '{"data":[[4]]}' \ http://0.0.0.0/score
如何将此代码转换为Python函数或使用Postman?你知道吗
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。你知道吗
curl
最短等价物(带requestslib)如下所示:
requests
import requests # pip install requests r = requests.post("http://0.0.0.0/score", json={"data":[[4]]})
requests将自动为此请求设置适当的Content-Type头。你知道吗
Content-Type
注意,在请求头中仍然会有一些差异,因为curl和requests总是隐式地设置它们自己的头集。你知道吗
您的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头。 但仍将使用压缩。你知道吗
headers=
User-Agent
应该大致相当于curl命令。你知道吗
否则,要将curl“翻译”成Python命令,可以使用https://curl.trillworks.com/#python之类的工具。你知道吗
Postman有一个方便的"import" tool来导入
curl
像您这样的命令(将您的命令粘贴为原始文本)。结果也可以使用Postman "exported" into Python code。你知道吗
最短等价物(带
requests
lib)如下所示:requests
将自动为此请求设置适当的Content-Type
头。你知道吗注意,在请求头中仍然会有一些差异,因为
curl
和requests
总是隐式地设置它们自己的头集。你知道吗您的
curl
命令将发送这组标头:而
requests
头将如下所示:因此,如果需要,您可以在
headers=
关键字参数中手动指定User-Agent
头。但仍将使用压缩。你知道吗
相关问题 更多 >
编程相关推荐