an error in sending json data to flask server [duplicate]

2024/10/5 19:57:51

I have a json data as

{"age":59.0,"bp":70.0,"sg":1.01,"al":3.0,"su":0.0,"rbc":1.0,"ba":0.0,"bgr":76.0,"bu":186.0,"sc":15.0,"sod":135.0,"pot":7.6,"hemo":7.1,"pcv":22.0,"wbcc":3800.0,"rbcc":2.1,"htn":1.0,"dm":0.0,"cad":0.0,"appet":0.0,"pe":1.0,"ane":1.0}

I have to send this json into a ML model that is inside a flask server to predict outcome class as 0 or 1.

so for that I wrote the following code in app.py

# flask route for ml model
import numpy as np
from flask import Flask, request, jsonify
from flask_cors import CORS
import keras
import astapp = Flask(__name__)
CORS(app)@app.route('/predict', methods=['POST'])
def predict():if request.method == 'POST':data_raw = request.get_json()print(data_raw)#convert json to dictnew_dict = ast.literal_eval(data_raw)# initialize a new list to store the dict valuesdata=[]for i in new_dict.values():data.append(i)# converted the values list to np array and reshaped itdata = np.array(data)data = np.array(data.reshape(1, -1))print(data)# load modelmodel = keras.models.load_model('model.pkl', 'rb')# make predictionprediction = model.predict(data)print(prediction)return jsonify({'prediction': prediction.tolist()})else:return jsonify({'prediction': 'error'})# run flask app
if __name__ == '__main__':app.run(debug=True)

But on sending that json as POST request to localhost:5000/predict I am getting an error as

ValueError: malformed node or string: {'age': 59.0, 'bp': 70.0, 'sg': 1.01, 'al': 3.0, 'su': 0.0, 'rbc': 1.0, 'ba': 0.0, 'bgr': 76.0, 'bu': 186.0, 'sc': 15.0, 'sod': 135.0, 'pot': 7.6, 'hemo': 7.1, 'pcv': 22.0, 'wbcc': 3800.0, 'rbcc': 2.1, 'htn': 1.0, 'dm': 0.0, 'cad': 0.0, 'appet': 0.0, 'pe': 1.0, 'ane': 1.0}

Though the same data preprocessing part of pushing the dict in the model.predict is working in the training code, but its creating an error here.

model url for use in reconstruction of code

Answer

The request.get_json() method is already doing the work of converting your JSON to a Python object. You can already use data_raw as a dictionary:

@app.route('/predict', methods=['POST'])
def predict():if request.method == 'POST':data_raw = request.get_json()print(type(data_raw))  # prints 'dict' in the terminal used to start the serverdata = np.array(data_raw.values()).reshape(1, -1)# do model stuff

The error you were getting is because ast.literal_eval() expects a valid string representation of a literal Python object. By passing what you didn't realize was already a dict object, Python complained that the input was malformed.

By the way, in general when working with JSON in other contexts, you should be using json.loads(some_json_string) and json.dumps(some_python_object_you_want_to_serialize). The ast.literal_eval() function is not something you should ever really need, generally speaking.

https://en.xdnf.cn/q/119867.html

Related Q&A

terminate a python program when it hanged using subprocess python

I have a main.py which open a new cmd (subprocess) when another program (test.py, in same directory) is hanged. To determining test.py is hanged or not, I used latest modified time (os.path.getmtime(te…

causes of Python IOError: [Errno 13] Permission denied

When attempting to write a file, I can get this same error when any of following conditions applies:The file exists and is marked read-only. I dont have write permission for the folder and therefore ca…

Python Invalid Syntax IF statement

Im trying to make a quiz in python but I keep getting invalid syntax errors.#This is for addition questions.if (question=add) <---- That is where i get the error for i in range(0,10):first_number_a…

record a web page using python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 3…

returning a string from askopenfilename() to a entry box

I have seen many postings on the use of askopenfilename(), however I still cant seem to find anything to help me display the full file path in an entry box once I have selected said file. below I have…

Overflow error in Python program

Please help me to understand why this code doesnt work. I know there is something very stupid wrong. This should be an implementation of the fourth order Runge kutta algorithm to solve Lorentz system o…

python login 163 mail server

When I use this script to login the 163 mail server,there is something wrong! My python env is python 2.7.8 Please help me!import imaplibdef open_connect(verbose=False):host = imap.163.comport = 993if …

How to get list of keys that share a value with another key within the same dictionary?

I have a dictionary of unique keys where some keys share the same value. For example:D = {ida:{key:1},idb:{key:2},idc:{key:3},idd:{key:3},ide:{key:4},idf:{key:4},idg:{key:4}}I want a list of keys that…

Sqlite3 Error: near question mark: syntax error [duplicate]

This question already has answers here:Parameterized query binding table name as parameter gives error(3 answers)How to use variables in SQL statement in Python?(5 answers)Closed last year.I am trying…

running bs4 scraper needs to be redefined to enrich the dataset - some issues

got a bs4 scraper that works with selenium - see far below: well - it works fine so far: see far below my approach to fetch some data form the given page: clutch.co/il/it-services To enrich the scrap…