将curl方法转换为python请求

2024-10-03 21:25:52 发布

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

我正在尝试将curl方法转换为python POST请求

下面是curl命令:

curl --location --request POST 'https://global.kaleyra.com/api/v4/' --form 'file=@/home/user/Desktop/TWP_MD565041.pdf' --form 'method=wa' --form 'api_key=A3d51xxxxxxxxxxxxxxxxxxxxxxxxxx' --form 'from=971xxxxxxxxxx' --form 'body={
 "to":"9198xxxxxxxx",
 "type": "document", "document" : {"caption" : ""},
  "callback":""
   }' --form 'format=json'

下面是我尝试过的python请求:

payload = {
             "method": "wa",
             "api_key": "A3dxxxxxxxxxxxxxxxx",
             "body": '{"to":'+str(user_number)+',"type": "document"}',
             'from': '971xxxxxxxx',
             'format':'json',
             "file":open("/home/user/Desktop/TWP_MD565041.pdf","rb")}
r = requests.post(url=api_url,headers={}, files=payload)

获取错误:

b'{"status":"A401B","message":"Method Not Found"}'

然后我改变了请求,如下所示:

    r = requests.post(url=api_url,headers={}, files=json.dumps(payload))

现在我得到一个错误:

TypeError: Object of type 'BufferedReader' is not JSON serializable

我试过这个

with open("/home/user/Desktop/TWP_MD565041.pdf",'rb') as f:

        r = session.post(url=api_url,headers=headers, data=json.dumps(payload),files={"file":f})

然后我得到一个错误:

ValueError: Data must not be a string.

我如何解决这个问题


Tags: formapijsonurlhomepdftypecurl
1条回答
网友
1楼 · 发布于 2024-10-03 21:25:52

1)请求将为您序列化JSON。删除json.dumps方法并使用原始负载

2)我建议这样发送文件。with语句用于较大的原子操作,在执行API I/O时确实不需要保持文件打开。因此,使用以下方法,因为文件流在解释后隐式关闭

r = session.post(
    url = api_url,
    headers = headers, 
    data = payload,
    files = {'file': open('file.pdf','rb')}
)

相关问题 更多 >