使用--form将curl转换为python请求

问题描述:

我有这样的卷曲请求:

curl -X POST http://mdom-n-plus-1.nonprod.appsight.us:8081/mesmerdom/v1/getByScreen -F"data = {\" screen \:{\"screen-id \:\" 57675 \}}"

我正在尝试使用类似以下的方法将其转换为python:

I am trying to convert it to python by using something like this:

import requests
import json
url = "http://mdom-n-plus-1.nonprod.appsight.us:8081/mesmerdom/v1/getByScreen"
payload = {"data": json.dumps({"screen":["screen-id", "57675"]})}
req = requests.post(url, data=payload)
print (req.text)

但出现以下错误:

io.finch.Error $ NotPresent:请求中不存在必需的参数数据".

在这种情况下,将bash curl调用转换为python请求的最佳方法是什么?

What would be the best way to convert the bash curl call to python request in this case?

欢迎使用 stackoverflow.com .

-F 开关表示 form-encoded 数据.

传递 data 将使 Content-Type:x-www-form-urlencoded 但似乎服务器正在接受 Content-Type:multipart/form-data 因此我们也需要传递 files .但是由于服务器正在 form 中查找实际数据,因此我们也需要传递 data .所以这应该工作:

passing data makes the Content-Type: x-www-form-urlencoded but it seems that server is accepting Content-Type: multipart/form-data so we need to pass files as well. but since server is looking for actual data inside form we need to pass data as well. So this should work:

import requests

url = "http://mdom-n-plus-1.nonprod.appsight.us:8081/mesmerdom/v1/getByScreen"

payload = { 'data' : '{"screen" : {"screen-id": "57675"}}'}

req = requests.post(url, files=dict(data='{"screen":{"screen-id":"57675"}}'), data=payload)
print (req.text)

希望这会有所帮助.