Quart¶
The Quart integration is typically imported as from mplbed import mplbed_quart
(although it is also available as mplbed.integration.quart).
To display a figure at a particular route:
import matplotlib.pyplot as plt
from quart import Quart
from mplbed import mplbed_quart
app = Quart(__name__)
mplbed_quart.setup(app)
@app.route("/figure")
@mplbed_quart.figure_page
async def figure():
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
return fig
The setup function installs the mplbed middleware, registers the template
context processor, and selects the interactive Matplotlib backend:
- mplbed.mplbed_quart.setup(app, *, do_install_middleware=True, prefix='/webagg', mplbed_starlette_app=None, mplbed_starlette_app_kwargs=None, manage_routing=True, do_register_context_processor=True, do_use_mpl_backend=True, use_webaggext_backend=True)¶
Setup the mplbed integration for the given Quart app.
This function performs all the integration steps necessary to use mplbed with Quart, including installing middleware, registering context processors, and configuring the matplotlib backend. The default parameter values are suitable for most use cases, but can be overridden as needed.
- Parameters:
app (Quart) – The Quart app to integrate with mplbed.
do_install_middleware (bool, optional) – Whether to install the mplbed middleware on the given app. Default is True.
prefix (str, optional) – The URL prefix for the routes handleded by mplbed. Default is ‘/webagg’.
mplbed_starlette_app (Starlette, optional) – The Starlette app to use for the mplbed routes, as returned by mplbed_starlette_app_factory. If not provided, a new app will be created using the provided mplbed_starlette_app_kwargs.
mplbed_starlette_app_kwargs (dict, optional) – Keyword arguments to pass to the Mplbed app factory if mplbed_starlette_app is not provided.
manage_routing (bool, optional) – Whether the ASGI middleware should manage routing. Default is True. If you set this to False, you are responsible for routing requests to the Mplbed app under the given prefix.
do_register_context_processor (bool, optional) – Whether to register the mplbed context processor on the given app. Default is True.
do_use_mpl_backend (bool, optional) – Whether to setup the matplotlib backend for rendering figures. Default is True.
use_webaggext_backend (bool, optional) – Whether to use webaggext rather than the basic webagg backend for rendering figures. Default is True.
The figure_page helper wraps a route handler that returns a Matplotlib figure
in a Quart Response:
- mplbed.mplbed_quart.figure_page(inner=None, **figure_page_kwargs)¶
Decorator to create a Quart Response object containing the HTML for the given figure using a function taking and returning raw strings.
This function can be called in three ways:
As a decorator for a function taking any number of arguments and returning a matplotlib Figure object, making it appropriate to use as a decorator for view/handler function.
As a decorator for a function taking no arguments and returning a matplotlib Figure object, making it appropriate to use as a decorator for a figure closure within a view/handler.
As a decorator factory taking keyword arguments to pass through to the underlying function figure_standalone, e.g.
@figure_page(template=...).
All usages are generic with regards to async/sync
Internally this decorator uses the function figure_standalone to generate the HTML and create the Quart Response.
Example
Usage 1:
@figure_page (async) def my_handler(request): return Figure()
Usage 2:
(async) def my_handler(request): # ... @figure_page (async) def create_figure(): return Figure() return (await) create_figure()
- Parameters:
prevent_default_navigation (bool, optional) – Prevent the browser’s default scrolling behavior for wheel, Arrow, PageUp/PageDown, Home/End, and Space events directed at the plot. Events are still sent to Matplotlib. Default is False.
borderless (bool, optional) – Hide the figure title bar and canvas border on the page. Default is True.
fit ({"none", "width", "container"}, optional) – Fit the parent width or both dimensions.
"container"requires a parent with an explicit height. Default is"none".resize_handle (bool or None, optional) – Show the figure’s manual resize handle.
None(default) shows it whenfit="none"and hides it for the fit modes.template (callable, optional) – A callable taking the raw strings head, title and fig as keyword arguments and returning the HTML template to use for rendering the figure page as a raw string. Will default to default_figure_page_template if not provided.
For a figure page rendered with a Jinja template, use figure_page_jinja. The
template receives mplbed_head and fig:
- mplbed.mplbed_quart.figure_page_jinja(inner=None, **figure_page_kwargs)¶
Decorator to create a Quart Response object containing the HTML for the given figure using a Jinja template.
This function can be called in three ways:
As a decorator for a function taking any number of arguments and returning a matplotlib Figure object, making it appropriate to use as a decorator for view/handler function.
As a decorator for a function taking no arguments and returning a matplotlib Figure object, making it appropriate to use as a decorator for a figure closure within a view/handler.
As a decorator factory taking keyword arguments to pass through to the underlying function figure_standalone_jinja, e.g.
@figure_page(template=...).
Internally this decorator uses the function figure_standalone_jinja to generate the HTML and create the Quart Response.
Example
Usage 1:
@figure_page def my_handler(request): return Figure()
Usage 2:
def my_handler(request): # ... @figure_page def create_figure(): return Figure() return create_figure()
- Parameters:
prevent_default_navigation (bool, optional) – Prevent the browser’s default scrolling behavior for wheel, Arrow, PageUp/PageDown, Home/End, and Space events directed at the plot. Events are still sent to Matplotlib. Default is False.
borderless (bool, optional) – Hide the figure title bar and canvas border on the page. Default is True.
fit ({"none", "width", "container"}, optional) – Fit the parent width or both dimensions.
"container"requires a parent with an explicit height. Default is"none".resize_handle (bool or None, optional) – Show the figure’s manual resize handle.
None(default) shows it whenfit="none"and hides it for the fit modes.template (str) – The path to a Jinja template which will be passed the template variables mplbed_head and fig.
app (Quart, optional) – The Quart app to use for rendering the Jinja template. If not provided, the app passed to setup(…) and/or MplbedMiddleware will be used. Typically this does not need to be provided.
iframe_for creates an iframe for a named Quart endpoint:
- mplbed.mplbed_quart.iframe_for(endpoint, *, app=None, **kwargs)¶
Generate an iframe HTML snippet for the given Quart endpoint.
- Parameters:
endpoint (str) – The name of the Quart endpoint to generate the iframe for.
app (Quart, optional) – The Quart app to use for URL generation. If not provided, the current app will be used.
**kwargs – Additional keyword arguments to pass to quart.url_for.
- Returns:
The HTML snippet for the iframe.
- Return type:
str
Further examples¶
Inline, iframe, and popup figures (basic.py)¶
Shows three embedding styles in a single Quart/Jinja app: an inline figure, a figure loaded inside an iframe, and a figure opened in a modal popup.
"""
Shows inline figures, external figures and popups using mplbed/Quart/jinja2.
"""
from quart import Quart, render_template
from mplbed import mplbed_quart
from mplbed import safe_html
app = Quart(__name__)
mplbed_quart.setup(app)
def mk_plot():
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2 * np.pi, 0.01)
s = np.sin(t)
fig, ax = plt.subplots()
ax.plot(t, s)
return fig
@app.route('/')
async def index():
return await render_template(
"index.html",
inline_fig=safe_html.figure_html(mk_plot()),
external_iframe=mplbed_quart.iframe_for("figure"),
open_inline_popup=safe_html.figure_html(mk_plot(), target="modal")
)
@app.route('/figure')
async def figure():
return mplbed_quart.figure_standalone(mk_plot())
if __name__ == "__main__":
import os
app.run(debug=True, port=int(os.environ.get("PORT", 8000)))
The Jinja templates used by the example:
templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4" crossorigin="anonymous"></script>
<title>{% block title %}{% endblock %}</title>
{{ mplbed_head(False) }}
</head>
<body style="padding: 1em; font-family: sans-serif;">
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
templates/index.html
{% extends "base.html" %}
{% block title %}Home{% endblock %}
{% block content %}
<h2 style="font-size: 2em;">Inline figure</h2>
{{ inline_fig }}
<hr style="margin: 5em 0;">
<h2 style="font-size: 2em;">External iframe</h2>
{{ external_iframe }}
<hr style="margin: 5em 0;">
<h2 style="font-size: 2em;">Open inline popup</h2>
{{ open_inline_popup }}
{% endblock %}