|
| 1 | +""" |
| 2 | +.. _howto-webapp: |
| 3 | +
|
| 4 | +================================================= |
| 5 | +How to use Matplotlib in a web application server |
| 6 | +================================================= |
| 7 | +
|
| 8 | +In general, the simplest solution when using Matplotlib in a web server is |
| 9 | +to completely avoid using pyplot (pyplot maintains references to the opened |
| 10 | +figures to make `~.matplotlib.pyplot.show` work, but this will cause memory |
| 11 | +leaks unless the figures are properly closed). Since Matplotlib 3.1, one |
| 12 | +can directly create figures using the `.Figure` constructor and save them to |
| 13 | +in-memory buffers. The following example uses Flask_, but other frameworks |
| 14 | +work similarly: |
| 15 | +
|
| 16 | +.. _Flask: http://flask.pocoo.org/ |
| 17 | +
|
| 18 | +""" |
| 19 | + |
| 20 | +import base64 |
| 21 | +from io import BytesIO |
| 22 | + |
| 23 | +from flask import Flask |
| 24 | +from matplotlib.figure import Figure |
| 25 | + |
| 26 | +app = Flask(__name__) |
| 27 | + |
| 28 | + |
| 29 | +@app.route("/") |
| 30 | +def hello(): |
| 31 | + # Generate the figure **without using pyplot**. |
| 32 | + fig = Figure() |
| 33 | + ax = fig.subplots() |
| 34 | + ax.plot([1, 2]) |
| 35 | + # Save it to a temporary buffer. |
| 36 | + buf = BytesIO() |
| 37 | + fig.savefig(buf, format="png") |
| 38 | + # Embed the result in the html output. |
| 39 | + data = base64.b64encode(buf.getbuffer()).decode("ascii") |
| 40 | + return f"<img src='data:image/png;base64,{data}'/>" |
| 41 | + |
| 42 | +# %% |
| 43 | +# When using Matplotlib versions older than 3.1, it is necessary to explicitly |
| 44 | +# instantiate an Agg canvas; |
| 45 | +# see e.g. :doc:`/gallery/user_interfaces/canvasagg`. |
| 46 | +# |
| 47 | +# Note: This script should be run using the |
| 48 | +# `flask command-line tool <https://flask.palletsprojects.com/en/master/cli/>`_ |
| 49 | +# since it is a Flask application. |
| 50 | +# Assuming that the working directory contains this script: |
| 51 | +# |
| 52 | +# Unix-like systems |
| 53 | +# |
| 54 | +# .. code-block:: console |
| 55 | +# |
| 56 | +# FLASK_APP=web_application_server_sgskip flask run |
| 57 | +# |
| 58 | +# Windows |
| 59 | +# |
| 60 | +# .. code-block:: console |
| 61 | +# |
| 62 | +# set FLASK_APP=web_application_server_sgskip |
| 63 | +# flask run |
| 64 | +# |
| 65 | +# .. _howto-click-maps: |
| 66 | +# |
| 67 | +# Clickable images for HTML |
| 68 | +# ------------------------- |
| 69 | +# |
| 70 | +# Andrew Dalke of `Dalke Scientific <http://www.dalkescientific.com>`_ |
| 71 | +# has written a nice `article |
| 72 | +# <http://www.dalkescientific.com/writings/diary/archive/2005/04/24/interactive_html.html>`_ |
| 73 | +# on how to make html click maps with Matplotlib agg PNGs. We would |
| 74 | +# also like to add this functionality to SVG. If you are interested in |
| 75 | +# contributing to these efforts that would be great. |
0 commit comments