I have a situation where i need to post image and json data to the database using single API request. when I try to post request without images it works fine. when I try to add images and json together it throws an error as when i send request using postman.
Can anyone suggest what could be the best way to resolve this issue ?
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'file
Server
@app.route("/testresult", methods=["POST"])
def testresult():
if request.method == "POST":
file = request.files['file']
traynumber = request.json['traynumber']
sample_number = request.json["sample_number"]
test_started = request.json['test_started']
test_ended= request.json['test_ended']
resultstatus = request.json['resultstatus']
traydetails = Traydetails.query.filter(Traydetails.traynumber ==traynumber).first_or_404()
trayid = traydetails.id
sampleimage = file.read()
add_sampleresult = Sampletestresult(trayid,sample_number,test_started,test_ended,resultstatus,sampleimage)
db.session.add(add_sampleresult)
db.session.commit()
return file.filename
Client :
import requests
url = 'http://localhost:5000/testresult'
ig = r'C:\Users\Admin\Pictures\test\cat.jpg'
files = {'file': open(ig, 'rb')}
payload = {"traynumber":"868032cd60444cfca6558ce575c13c0a_1","sample_number":1,"test_started":"2021-06-24 15:30:20","test_ended": "2021-06-24 16:30:20","resultstatus": 1}
value = requests.post(url,files=files,json=payload,verify=False,)
print(value.content)