[英]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.