繁体   English   中英

将 curl 方法转换为 python 请求

[英]Convert curl method into python request

我正在尝试将 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":"方法未找到"}'

然后我改变了这样的请求:

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

现在我收到一个错误:

TypeError:“BufferedReader”类型的 Object 不是 JSON 可序列化的

我试过这个,

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:数据不能是字符串。

我该如何解决这个问题?

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM