将curl转换为python请求

2024-04-25 20:59:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将下面的curl请求转换成python请求(使用请求)

curl -X POST -H "Authorization: Bearer <TOKEN>" -H "Cache-Control: no-cache" -H "Content-Type: multipart/form-data" -F "modelId=CommunitySentiment" -F "document=the presentation was great and I learned a lot"  https://api.einstein.ai/v2/language/sentiment

响应将是一个json {“概率”:[{ “label”:“肯定”, “概率”:0.8673582 }, { “label”:“阴性”, “概率”:0.1316828 }, { “neutral”:“neutral label”, “概率”:0.0009590242 } ] }在

我的python脚本如下所示,但是它返回一个400个错误请求。在

^{pr2}$

我觉得我错过了一些东西,或者把某些东西转换错了。。。在

任何帮助都将不胜感激。在

谢谢你


Tags: notokencachetypecontentcurl概率post
3条回答

使用json.dumps()函数将此JSON对象转换为字符串:

files = json.dumps({'modelId':'CommunitySentiment','document': 'the presentation was great and I learned a lot'})

在请求.post()想要的是dict,而不是字符串。将上一行替换为:

^{pr2}$

您可以使用以下实用程序:

https://curl.trillworks.com/

我一直在用它。附上一个例子。enter image description here

可以使用files参数发送多部分表单数据,例如比较:

$ curl -F "document=the presentation was great and I learned a lot" -F "modelId=CommunitySentiment" http://httpbin.org/post
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "document": "the presentation was great and I learned a lot", 
    "modelId": "CommunitySentiment"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Connection": "close", 
    "Content-Length": "303", 
    "Content-Type": "multipart/form-data; boundary=            11650e244656399f", 
    "Expect": "100-continue", 
    "Host": "httpbin.org", 
    "User-Agent": "curl/7.55.1"
  }, 
  "json": null, 
  "origin": "X.X.X.X", 
  "url": "http://httpbin.org/post"
}

Python请求:

^{pr2}$

你的例子是:

In []:
headers = {
    'Authorization': 'Bearer <TOKEN>',
    'Cache-Control': 'no-cache'
}
files = {
    'modelId': (None, 'CommunitySentiment'),
    'document': (None, 'the presentation was great and I learned a lot')
}
requests.post('https://api.einstein.ai/v2/language/sentiment', headers=headers, files=files, verify=False).json()

Out[]:
{'object': 'predictresponse',
 'probabilities': [{'label': 'positive', 'probability': 0.8673582},
  {'label': 'negative', 'probability': 0.1316828},
  {'label': 'neutral', 'probability': 0.0009590242}]}

相关问题 更多 >