如何将此cURL请求转换为python请求

时间:2018-09-11 15:08:50

标签: python curl

我尝试转换的请求是

curl -X POST "http://127.0.0.1:8881/models/NOVANTATREH/v1/predict" -H "Content-Type:multipart/form-data" -F "data={\"key\": \"Photo\"};type=application/json" -F "Photo=@/path/to/image.png" 

然后我将其转换为:

import requests

headers = {
    'Content-Type': 'multipart/form-data',
}

files = {
    'data': (None, '{"key": "Photo"};type'),
    'Photo': ('/path/to/image.png', open('/path/to/image.png', 'rb')),
}

response = requests.post('http://127.0.0.1:8881/models/NOVANTATREH/v1/predict', headers=headers, files=files)

但是当我改变时 /path/to/image.png到我的实际路径 我收到了400错误响应。关于我在做什么的任何提示?(使用curl通常可以正常工作,因此这不是服务器端问题)

2 个答案:

答案 0 :(得分:0)

你可以试试吗?

import requests

url = "http://127.0.0.1:8881/models/NOVANTATREH/v1/predict"

payload = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"data\"\r\n\r\n{\"key\": \"Photo\"};type=application/json\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"Photo\"\r\n\r\n@/path/to/image.png\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--"
headers = {
    'content-type': "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
    'Content-Type': "multipart/form-data",
    'Cache-Control': "no-cache"
    }

response = requests.request("POST", url, data=payload, headers=headers)

print(response.text)

答案 1 :(得分:0)

import requests

url = 'http://127.0.0.1:8881/models/NOVANTATREH/v1/predict'    
filepath = '/path/to/image.png' 
filename = 'image.png'    
data = {"key": "Photo"}

files = {
    'file': (filename, open(filepath, 'rb'), 'image/png'),
}

response = requests.post(url, files=files, data=data)