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 (https://colab.research.google.com/). 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 (https://streamlit.io/). 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:
prerequisites:
python3 - venv flask_env
source flask_env/bin/activate
pip3 install flask numpy matplotlib

project structure:

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

app.py

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

app = Flask(__name__)

@app.route('/plot')
def plot():
    linspace=[1,2,3,4,5,6,7,8,9,10]
    sin_wave=np.sin(linspace)

    # plot
    plt.plot(linspace, sin_wave)

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

if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=True)    

plot.html

<!doctype html>
<html>
   <body>

      <h1>Chart</h1>

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

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

   </body>
</html>

start the app:
python3 app.py

and then go to
http://localhost:5000/plot
to check your graph in website.

Sources:
https://stackoverflow.com/questions/50728328/python-how-to-show-matplotlib-in-flask