Issue
I'm facing KeyError
error here
File "C:\Users\ayush\Python\iris_server.py", line 11, in predict
predict_request=[[data["sepal_length"],data["sepal_width"],data["petal_length"],data["petal_width"]]]
KeyError: 'sepal_length'
when I run my client side code which has hardcoded values of the data fields
Flask Server side:
from flask import Flask, request, jsonify
import numpy as np
import pickle
import os
os.chdir('C:/Users/bhosl/Python')
model = pickle.load(open('iris_model','rb'))
app = Flask(__name__)
@app.route('/api',methods=['POST'])
def predict():
data = request.get_json(force=True)
predict_request=[[data["sepal_length"],data["sepal_width"],data["petal_length"],data["petal_width"]]]
req=np.array(predict_request)
print(req)
prediction = model.predict(predict_request)
pred = prediction[0]
print(pred)
return jsonify(int(pred))
if __name__ == '__main__':
app.run(port=5000, debug=True)
Client side
import requests
import json
r = requests.post('http://localhost:5000/api', json={
"sepal_lenth":3.2,
"sepal_width":7.3,
"petal_length":4.5,
"petal_width":2.1
})
print(r.json)
print(r.status_code)
while the client side gives
<bound method Response.json of <Response [500]>>
500 as the output
so assuming the code isn't the problem here,
How can I fix this
Thanks in Advance
Solution
You misspelled sepal_length
as sepal_lenth
on the client side.
KeyError is caused by python not being able to find a key in the dictionary. In your case, it cannot find the key sepal_length
. The <Response [500]>
because your sever encountered an Internal Server Error(KeyError), returning the status code of 500.
This should work:
import requests
import json
r = requests.post('http://localhost:5000/api', json={
"sepal_length":3.2,
"sepal_width":7.3,
"petal_length":4.5,
"petal_width":2.1
})
print(r.json)
print(r.status_code)
Answered By - Parzival
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.