Converting curl with --form to python requests

拜拜、爱过 提交于 2021-01-28 13:41:39

问题


I have a curl request like this:

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

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)

but I get the following error:

io.finch.Error$NotPresent: Required param 'data' not present in the request.

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


回答1:


Welcome to stackoverflow.com.

-F switch of curl denotes form-encoded 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)

hope this helps.



来源:https://stackoverflow.com/questions/61934261/converting-curl-with-form-to-python-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!