【问题标题】:How to create a function in python equivalent to this curl call?如何在 python 中创建与此 curl 调用等效的函数?
【发布时间】:2019-11-08 15:07:34
【问题描述】:

我遇到了以下代码的问题:

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

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

【问题讨论】:

标签: python curl python-requests postman


【解决方案1】:

最短的等效项(使用requests lib)如下所示:

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 标头。
但仍会使用压缩。

【讨论】:

    【解决方案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 类似您的命令(将您的命令粘贴为原始文本)。
    结果也可以是 "exported" into Python code 使用 Postman。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      • 2018-12-15
      相关资源
      最近更新 更多