I am creating a grade prediction app where I have a React form frontend and a Flask API where I send data to the api and it returns me a grade after predicting it with a random forest classifier. I have never created a flask api before and I cant find an answer to this. Here is my flask api code:
from flask import Flask, request, jsonify, make_response
import joblib
import numpy as np
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
classifier = joblib.load("random_forest_grade.joblib")
@app.route("/", methods = ['GET'])
def home():
return "Hello world"
@app.route("/grades", methods=['POST', "GET"])
def grades():
if request.method == "POST":
try:
formData = request
data = [val for val in formData.values()]
prediction = classifier.predict(np.array(data).reshape(1, -1))
types = {0:"A",1:"B",2:"C",3:"D",4:"F"}
response = jsonify({
"statusCode": 200,
"status": "Prediction made",
"result": types[prediction[0]]
})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
except Exception as error:
return jsonify({
"statusCode": 500,
"status": "Could not make prediction",
"error": str(error)
})
if __name__ == "__main__":
app.run(debug=True)
And this is my React function which calls the flask api
submitForm = () =>{
const {formData,step, isLoading, result} = this.state
this.setState({isLoading:true, step: step+1})
const newCurrent = Math.ceil(formData.current/5)-3
this.setState({formData: {...formData, current: newCurrent}})
axios.post('http://127.0.0.1:5000/', formData)
.then(response => {
this.setState({
result: response.result,
isLoading: false
});
}).catch(err =>{
this.setState({
result: "Does not work",
isLoading: false
});
});
}
我认为您必须修复 URL,从http://127.0.0.1:5000/到http://127.0.0.1:5000/grades
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.