Build a Flask app with real-time ML inference using our step-by-step guide. Discover expert tips, code samples & best practices.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
model.pkl. This file contains your ML model object, pre-trained and ready for inference.pickle module to load the model once when the Flask application starts. This avoids reloading the model on each request.
// Import necessary modules
from flask import Flask, request, jsonify // Flask framework for web handling
import pickle // For loading the pre-trained model
// Initialize Flask app
app = Flask(**name**)
// Load the ML model from disk once during startup
try:
model = pickle.load(open("model.pkl", "rb"))
except Exception as e:
// Handle model loading errors gracefully
raise Exception("Failed to load ML model: " + str(e))
// Define route for ML inference
@app.route("/infer", methods=['POST'])
def infer():
try:
// Extract JSON data from the request
data = request.get\_json()
// Validate input: check if 'features' key is provided
if "features" not in data:
return jsonify({"error": "Missing 'features' in request"}), 400
// Pre-process input: for example, convert the list of features as required.
input\_features = data["features"]
// Depending on your model's requirement, you might need to reshape or normalize the features.
// For demonstration, we assume that input\_features is already in the correct format.
// Execute real-time inference
prediction = model.predict([input\_features])
// Return the prediction result as a JSON response
return jsonify({"prediction": prediction[0]})
except Exception as e:
// If an error occurs, return an error message
return jsonify({"error": str(e)}), 500
// Running the Flask app if executed as main program
if **name** == "**main**":
app.run(debug=True) // In production, disable debug mode for security
From startups to enterprises and everything in between, see for yourself our incredible impact.
Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â