在Python脚本中使用Curl命令

时间:2019-07-16 16:28:23

标签: python curl

尝试运行curl命令以获取响应并将其保存到文件中

无法创建代码,因为这是第一次尝试在python中使用curl命令,不知道从哪里开始

curl -X POST --header "Content-Type: application/json" --header "Accept: application/json" -d "
{ \"Products\": [], \"DataProducts\": [], \"includeExtractFields\": true, \"includedDocumentTypes\": [], \"removeOrphans\": true, \"searchDataProduct\": \"Model|test\", \"searchField\": \"ID_TEST\", \"searchValues\": [ \"123456789\",\"987654321\" ] }
" "http://test"

curl命令应返回json,然后将其保存到文件中

1 个答案:

答案 0 :(得分:2)

您应该考虑在本机Python中执行此操作,而不是在外部执行curl。这是一个如何使用Python和requests软件包发出POST请求的示例:

import requests
import json
response = requests.post('https://yoururl', data = {'key':'value'})
with open('output.json', 'w') as f:
    json.dump(response.json(), f)

您可以阅读requests文档来读/写标题等。

针对您的具体情况:

import requests
import json

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

data = {
    "Products": [],
    "DataProducts": [],
    "includeExtractFields": True,
    "includedDocumentTypes": [],
    "removeOrphans": True,
    "searchDataProduct": "Model|test",
    "searchField": "ID_TEST",
    "searchValues": [ "123456789","987654321" ]
}

# To send data form-encoded
response = requests.post('http://test/', headers=headers, data=data)

# To send data json-encoded
response = requests.post('http://test/', headers=headers, json=data)

# Save response as JSON file
with open('output.json', 'w') as f:
    json.dump(response.json(), f)