1
1
"""
2
- .. _howto-webapp:
2
+ =============================================
3
+ Embedding in a web application server (Flask)
4
+ =============================================
3
5
4
- =================================================
5
- How to use Matplotlib in a web application server
6
- =================================================
6
+ When using Matplotlib in a web server it is strongly recommended to not use
7
+ pyplot (pyplot maintains references to the opened figures to make
8
+ `~.matplotlib.pyplot.show` work, but this will cause memory leaks unless the
9
+ figures are properly closed).
7
10
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:
11
+ Since Matplotlib 3.1, one can directly create figures using the `.Figure`
12
+ constructor and save them to in-memory buffers. In older versions, it was
13
+ necessary to explicitly instantiate an Agg canvas (see e.g.
14
+ :doc:`/gallery/user_interfaces/canvasagg`).
15
15
16
- .. _Flask: http://flask.pocoo.org/
16
+ The following example uses Flask_, but other frameworks work similarly:
17
+
18
+ .. _Flask: https://flask.palletsprojects.com
17
19
18
20
"""
19
21
@@ -39,14 +41,10 @@ def hello():
39
41
data = base64 .b64encode (buf .getbuffer ()).decode ("ascii" )
40
42
return f"<img src='data:image/png;base64,{ data } '/>"
41
43
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`.
44
+ #############################################################################
46
45
#
47
- # Note: This script should be run using the
46
+ # Since the above code is a Flask application, it should be run using the
48
47
# `flask command-line tool <https://flask.palletsprojects.com/en/master/cli/>`_
49
- # since it is a Flask application.
50
48
# Assuming that the working directory contains this script:
51
49
#
52
50
# Unix-like systems
@@ -62,7 +60,6 @@ def hello():
62
60
# set FLASK_APP=web_application_server_sgskip
63
61
# flask run
64
62
#
65
- # .. _howto-click-maps:
66
63
#
67
64
# Clickable images for HTML
68
65
# -------------------------
0 commit comments