Django¶
The Django integration is typically imported as
from mplbed import mplbed_django (although it is also available as
mplbed.integration.django). It requires an ASGI deployment.
Wrap the Django ASGI application in the project’s asgi.py:
import os
from django.core.asgi import get_asgi_application
from mplbed import mplbed_django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
application = mplbed_django.setup(get_asgi_application())
To display a figure at a particular route, decorate a Django view that returns a Matplotlib figure:
import matplotlib.pyplot as plt
from django.urls import path
from mplbed import mplbed_django
@mplbed_django.figure_page
def figure(request):
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
return fig
urlpatterns = [path("figure/", figure, name="figure")]
The setup function installs the mplbed middleware and selects the interactive
Matplotlib backend. Unlike the other framework integrations, it returns the
wrapped ASGI application:
- mplbed.mplbed_django.setup(application=None, *, do_install_middleware=True, prefix='/webagg', mplbed_starlette_app=None, mplbed_starlette_app_kwargs=None, manage_routing=True, do_use_mpl_backend=True, use_webaggext_backend=True)¶
Setup the mplbed integration for a Django ASGI application.
This function performs all the integration steps necessary to use mplbed with Django, including installing middleware and configuring the matplotlib backend. The default parameter values are suitable for most use cases, but can be overridden as needed.
Unlike the other integrations, the wrapped application is returned rather than mutated, so that it can be exported from your
asgi.py, e.g.:application = mplbed_django.setup(get_asgi_application())
- Parameters:
application (ASGI3Application, optional) – The Django ASGI application to integrate with mplbed, e.g. the result of django.core.asgi.get_asgi_application. If not provided it will be fetched via get_asgi_application, which requires
DJANGO_SETTINGS_MODULEto be set in the environment.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_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 view that returns a Matplotlib figure in a
Django HttpResponse:
- mplbed.mplbed_django.figure_page(inner=None, **figure_page_kwargs)¶
Decorator to create a Django HttpResponse 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 Django HttpResponse.
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.
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 the Django template language, use
figure_page_dtl. The template receives mplbed_head and fig:
- mplbed.mplbed_django.figure_page_dtl(inner=None, **figure_page_kwargs)¶
Decorator to create a Django HttpResponse object containing the HTML for the given figure using a Django 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_dtl, e.g.
@figure_page(template=...).
All usages are generic with regards to async/sync
Internally this decorator uses the function figure_standalone_dtl to generate the HTML and create the Django HttpResponse.
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.
template (str) – The name of a Django template which will be passed the template variables mplbed_head and fig.
iframe_for creates an iframe for a named Django URL:
- mplbed.mplbed_django.iframe_for(endpoint, **kwargs)¶
Generate an iframe HTML snippet for the given Django URL name.
- Parameters:
endpoint (str) – The name of the Django URL to generate the iframe for.
**kwargs – Additional keyword arguments to pass to django.urls.reverse.
- Returns:
The HTML snippet for the iframe.
- Return type:
markupsafe.Markup
Further examples¶
Inline, iframe, and popup figures (asgi.py + mysite/)¶
The complete example runs Django under Daphne. It configures the ASGI middleware, registers the mplbed template context processor, and demonstrates inline, iframe, popup, raw figure-page, and Django-template figure-page usage.
asgi.py
"""
Runs the mplbed/Django example under Daphne, following the Django
documentation on deploying with ASGI/Daphne:
https://docs.djangoproject.com/en/6.0/howto/deployment/asgi/daphne/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
from mplbed import mplbed_django
application = mplbed_django.setup(get_asgi_application())
mysite/settings.py
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = "django-insecure-mplbed-demo"
DEBUG = True
ALLOWED_HOSTS = ["*"]
ROOT_URLCONF = "mysite.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR / "mysite" / "templates"],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.request",
"mplbed.integration.django.context_processor",
],
},
},
]
mysite/urls.py
from django.urls import path
from mysite import views
urlpatterns = [
path("", views.index),
path("figure", views.figure, name="figure"),
path("figure-dtl", views.figure_dtl, name="figure_dtl"),
]
mysite/views.py
"""
Shows inline figures, external figures and popups using mplbed/Django.
"""
from django.shortcuts import render
from mplbed import mplbed_django
from mplbed import safe_html
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
def index(request):
return render(
request,
"index.html",
{
"inline_fig": safe_html.figure_html(mk_plot()),
"external_iframe": mplbed_django.iframe_for("figure"),
"open_inline_popup": safe_html.figure_html(mk_plot(), target="modal"),
},
)
@mplbed_django.figure_page
def figure(request):
return mk_plot()
@mplbed_django.figure_page_dtl(template="figure.html")
def figure_dtl(request):
return mk_plot()
The Django templates used by the example:
mysite/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}</title>
{{ mplbed_head }}
</head>
<body style="padding: 1em; font-family: sans-serif;">
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
mysite/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 %}
mysite/templates/figure.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Figure</title>
{{ mplbed_head }}
</head>
<body>
{{ fig }}
</body>
</html>