我有一個呼叫 POST 端點但收到 400 錯誤的腳本。同時,對應的cURL請求成功。
首先,這是cURL:
curl -X 'POST' \
'http://localhost:8080/api/predict?Key=123testkey' \
-H 'accept: application/json' \
-H 'Content-Type: multipart/form-data' \
-F '[email protected];type=image/jpeg'
并翻譯成請求:
import requests
url = 'http://localhost:8080/api/predict?Key=123testkey'
headers = {
'accept': 'application/json',
'Content-Type': 'multipart/form-data',
}
params = {'Key' : '123testkey'}
files = {'image': open('156ac81cde4b3f22faa4055b53867f38.jpg', 'rb')}
response = requests.post(url, files=files, params=params, headers=headers)
還嘗試使用不包含密鑰的 URL,因為密鑰已在 params 中指定:
import requests
url = 'http://localhost:8080/api/predict'
headers = {
'accept': 'application/json',
'Content-Type': 'multipart/form-data',
}
params = {'Key' : '123testkey'}
files = {'image': open('156ac81cde4b3f22faa4055b53867f38.jpg', 'rb')}
response = requests.post(url, files=files, params=params, headers=headers)
我認為這應該很簡單,但無論我嘗試什么,我總是收到 400 請求錯誤。有什么建議?
編輯:也嘗試過 'image/jpeg' 而不是 'image' 無濟于事。
編輯:不幸的是,用“檔案”替換“影像”鍵也不起作用
編輯:它在郵遞員桌面上作業得很好,并生成以下代碼。但是,此代碼也會引發錯誤。
郵遞員生成的代碼:
import requests
url = "http://localhost:8080/api/predict?Key=123test"
payload={}
files=[
('file',('images19.jpg',open('156ac81cde4b3f22faa4055b53867f38.jpg','rb'),'image/jpeg'))
]
headers = {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)
以及郵遞員先前生成的代碼中的錯誤:
{"detail":"There was an error parsing the body"}
任何幫助弄清楚發生了什么都將不勝感激!
uj5u.com熱心網友回復:
您的問題在于您需要使用鍵“檔案”而不是“影像”添加的變數檔案,這是 curl 和 Python 代碼之間的區別,還要洗掉標頭,因為當您傳遞檔案引數時,請求會設定正確的標頭用于發送檔案。例如:
import requests
url = 'http://localhost:8080/api/predict?Key=123testkey'
params = {'Key' : '123testkey'}
files = {'file': open('156ac81cde4b3f22faa4055b53867f38.jpg', 'rb')}
response = requests.post(url, files=files, params=params)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314015.html
下一篇:服務發布方法的負面場景
