Home > Back-end >  How is the trick of using the matplotlib library in FLASK?
How is the trick of using the matplotlib library in FLASK?

Time:09-21

i'm want import matplotlib in flask app but i get this error: RuntimeError: main thread is not in main loop

CodePudding user response:

I would use Flask and matplotlib like this:

#!/usr/bin/env python3
################################################################################
# To run:
# export FLASK_APP=Flask-matplotlib.py
# flask run
#
# Open browser and go to:
# http://127.0.0.1:5000/plot
################################################################################

import io
import numpy as np
from flask import Flask, Response
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib import pyplot as plt

plt.rcParams["figure.autolayout"] = True
plt.rcParams["figure.figsize"] = [12,10]

app = Flask(__name__)

@app.route('/plot')
def plot_fig():
   fig = Figure()
   axis = fig.add_subplot(1, 1, 1)

   # Generate time for x axis
   time = np.arange(0, 10, 0.1);

   # Generate sine wave
   amplitude = np.sin(time)

   # Plot it
   axis.plot(time, amplitude)
   output = io.BytesIO()
   FigureCanvas(fig).print_png(output)
   return Response(output.getvalue(), mimetype='image/png')

enter image description here

CodePudding user response:

You probably need to use a non-interactive backend like Agg.

In my flask application I set the backend after import:

import matplotlib
from matplotlib import pyplot as plt
matplotlib.use('Agg')

After creating the plot you can save it as a file to a location where flask can find it and serve it out.

  • Related