How to plot matplotlib in a django web application?

I read the Matplotlib book for Python developers , but I try to follow the example in the "Matplotlib in a Django Application" section in chapter 8.

So far I have published a team

django-admin startproject mpldjango

and in the catalog mpldjango

python manage.py startapp mpl

According to the example in, mpldjango/mplI did views.pyas follows:

import django
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import numpy as np

def mplimage(request):
    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    x = np.arange(-2,1.5,.01)
    y = np.sin(np.exp(2*x))
    ax.plot(x, y)
    response=django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

Further, the book says that mpldjango/urls.pythis line should be added:

urlpatterns = patterns('',
       (r'mplimage.png', 'mpl.views.mplimage'),
)

However, I do not see how this will work, because the 'default' urls.py, urlpatternsthere litas django.conf.urls.urlobjects:

from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

patterns . , ( 2009 ) API Django? , , ? ( , python manage.py runserver localhost:8000/mplimage.png ).

+4
1

, Django. "" , mpldjango/urls.py :

from django.conf.urls import include, url
from django.contrib import admin
import mpl.views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'mplimage.png', mpl.views.mplimage),
]

, http://localhost:8000/mplimage.png, :

enter image description here

+5

Source: https://habr.com/ru/post/1682850/


All Articles