Create simple data science web app with python flask

Let's say we have nice python algorithm running machine learning analytics on our finance data (or whichever data analytics purpose). The algos are creating beautiful graphs with matplotlib. But how do I show all these analytics to the world?

I can present it as a jupyter notebook in Google collab ( Great benefit is that users can run your notebooks directly and can also enable GPU acceleration for free, which is amazing for machine learning applications. Users can even modify your code on the fly.

We can also create data analytics web app with streamlit ( It is super easy, all is written with python, this is low code solution. Streamlit would be my first go to app for creating data science prototypes.

But sometimes we would want to create regular website for our data analytics app. With proper frontend, backend, API endpoints, authentication, database ORM layer and so on.

For such purposes is ideal Flask as a backend that would run some computations and resulting graphs will inject to html templates on frontend (there is no frontend server, just plain HTML files as templates).

Simplest working Flask example with some visualization:
python3 - venv flask_env
source flask_env/bin/activate
pip3 install flask numpy matplotlib

project structure:

$ tree .
├── static
│   └── images
│       └── plot.png
└── templates
    └── plot.html
3 directories, 3 files

from flask import Flask
from flask import render_template
import numpy as np
import matplotlib.pyplot as plt

app = Flask(__name__)

def plot():

    # plot
    plt.plot(linspace, sin_wave)

    # we have to use relative path to our
    return render_template('plot.html', name = 'plot', url ='../static/images/plot.png')

if __name__ == '__main__':"", debug=True)    


<!doctype html>


      <p>{{ name }}</p>

      <img src={{ url }} alt="Chart">


start the app:

and then go to
to check your graph in website.