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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…