How to Make a Python Flask App (For ML Model Deployment & Other Things)

Paul Yang - November 15th, 2023

Flask is a lightweight Python framework, and one of its uses is making it simple to create and deploy machine learning models as web services. With its simplicity and ease of use, you can have your model up and running in no time. In this guide, we'll walk through how to use Flask to serve a model.

Einblick allows you to deploy these models directly from our canvas, meaning you no longer need to use third-party services or manage additional deployment resources in order to bring your model to production. Want to try it yourself? Simply clone this canvas and try it yourself.

NOTE: Even the Einblick free tier allows you to create Endpoints, but will expire after 30 minutes of inactivity.

Jump to Just the Python Code

1. Quickly Create a Machine Learning Model to Deploy

We use the Iris dataset and XGBoost to create a classification model, and then use joblib to save that model to disk. If you need help training a model on your own data, just reach out to us at support@einblick.ai.

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

# Load the Iris dataset 
iris = load_iris() 
X, y = iris.data, iris.target 
# Train XGBoost classifier
xgb_classifier = xgb.XGBClassifier() 
xgb_classifier.fit(X, y)

joblib.dump(xgb_classifier, 'xgb_model.joblib') # Save to a file

2. Creating the /predict Endpoint

The following Flask code snippet demonstrates how to deploy a machine learning model for species prediction. The model, loaded via joblib, takes in specific features—sepal length, sepal width, petal length, and petal width—calculates the prediction, and responds with the predicted species.

Upon receiving a POST request at the /predict endpoint and providing input data conforming to the IrisData schema, this function uses the classifier to predict the species of an Iris flower.

app = Flask(__name__)

# Load the model during startup
xgb_classifier = joblib.load('xgb_model.joblib')

### Endpoint to predict using the loaded XGBoost model
@app.route("/predict", methods=['POST'])
def predict_species():
  data = request.get_json()
  features = np.array([[
      data['sepal_length'],
      data['sepal_width'],
      data['petal_length'],
      data['petal_width']
  ]])
  prediction = xgb_classifier.predict(features)
  return jsonify({"predicted_species": int(prediction[0])})

Within Einblick, you must first enable incoming connections to your Canvas by going to Kernel Settings → Incoming Connections. Remember to keep your URL string safe, as the unique prefix acts as your API key.

Einblick Incoming Connections Tab ScreenshotEinblick Incoming Connections Tab Screenshot

3. Start the App

Finally, we start the app. For Einblick, you want to use host="0.0.0.0", port=7000. You will access the endpoint by posting data to https://your-einblick-endpoint-string.proxy.einblick.ai/predict

if __name__ == "__main__":
  app.run(host="0.0.0.0", port=7000)

Call the endpoint and observe that we receive a response. For this example new data point, we receive false when I use curl to post the new data to the endpoint from my Mac Terminal:

4. Creating Webpages

Flask also effortlessly facilitates the creation of web pages. For instance, the endpoint /hello generates a simple "Hello!" webpage.

### Create an HTML page that just says "Hello!"
@app.route("/hello")
def hello():
  return """
  <html>
  <head><title>Hello Page</title></head>
  <body><h1>Hello!</h1></body>
  </html>"""

Just the Python Code

!pip install flask xgboost

from flask import Flask, request, jsonify
###
### Imports
###
import xgboost as xgb
import joblib
import numpy as np

###
### Create Model
### Replace this with your model 
xgb_classifier = xgb.XGBClassifier()
xgb_classifier.fit(X_train, y_train)
joblib.dump(xgb_classifier, 'xgb_model.joblib')

###
### Start the Endpoint
###
app = Flask(__name__)

# Load the model during startup
xgb_classifier = joblib.load('xgb_model.joblib')

### Endpoint to predict using the loaded XGBoost model
@app.route("/predict", methods=['POST'])
def predict_species():
   data = request.get_json()
   features = np.array([[
       data['sepal_length'],
       data['sepal_width'],
       data['petal_length'],
       data['petal_width']
   ]])
   prediction = xgb_classifier.predict(features)
   return jsonify({"predicted_species": prediction[0]})

### Return "Hello World"
@app.route("/")
def root():
   return {"message": "Hello World"}

### Create an HTML page that just says "Hello!"
@app.route("/hello")
def hello():
   return """
   <html>
   <head><title>Hello Page</title></head>
   <body><h1>Hello!</h1></body>
   </html>"""

### Run!
if __name__ == "__main__":
   app.run(host="0.0.0.0", port=7000)

About

Einblick is an AI-native data science platform that provides data teams with an agile workflow to swiftly explore data, build predictive models, and deploy data apps. Founded in 2020, Einblick was developed based on six years of research at MIT and Brown University. Einblick is funded by Amplify Partners, Flybridge, Samsung Next, Dell Technologies Capital, and Intel Capital. For more information, please visit www.einblick.ai and follow us on LinkedIn and Twitter.

Start using Einblick

Pull all your data sources together, and build actionable insights on a single unified platform.

  • All connectors
  • Unlimited teammates
  • All operators