Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

python - How to render a Matplotlib plot in a Django web application?

I'm reading the book Matplotlib for Python Developers but am struggling to follow the example in the section "Matplotlib in a Django application" in chapter 8.

So far, I've issued the command

django-admin startproject mpldjango

and, in the mpldjango directory,

python manage.py startapp mpl

As per the example, in mpldjango/mpl I've made the views.py as 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

Next, the book says that the mpldjango/urls.py should have this line added to it:

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

However, I don't see how this would work since in the 'default' urls.py, urlpatterns is a lits of django.conf.urls.url objects:

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

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

and there is no patterns constructor defined. Perhaps this book (which is from 2009) is referring to a legacy Django API? If so, how would I modify this code to make it work? (That is, after python manage.py runserver I should be able to browse to localhost:8000/mplimage.png and see an image of a chirped sinusoid).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to cannot import name patterns this is indeed a legacy interface of Django. I 'updated' it by making mpldjango/urls.py as follows:

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),
]

Now if I browse to http://localhost:8000/mplimage.png I see the plot as desired:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...