如何在Django Web应用程序中呈现Matplotlib图?

时间:2017-08-02 11:52:45

标签: python django matplotlib

我正在阅读这本书Matplotlib for Python Developers,但我正在努力遵循Django应用程序"中的#34; Matplotlib部分中的示例。在第8章。

到目前为止,我已发出命令

<div class="container">
  <div>
    some content
  </div>
  <div>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec cursus eu leo ac ultrices. Vivamus ornare, orci sed pretium sollicitudin
  </div>
</div>

<div class="container">
  <div>
    some content
  </div>
  <div></div>
</div>

,在django-admin startproject mpldjango 目录中,

mpldjango

根据示例,在python manage.py startapp mpl 我已经mpldjango/mpl如下:

views.py

接下来,该书说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 应该添加这一行:

mpldjango/urls.py

但是,我不知道这是如何运作的,因为在默认情况下&#39; urlpatterns = patterns('', (r'mplimage.png', 'mpl.views.mplimage'), ) urls.pyurlpatterns个对象:

django.conf.urls.url

并且没有定义from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ] 构造函数。也许这本书(来自2009年)指的是传统的Django API?如果是这样,我将如何修改此代码以使其工作? (也就是说,patterns之后,我应该可以浏览python manage.py runserver并查看啁啾正弦曲线的图像。

1 个答案:

答案 0 :(得分:5)

根据cannot import name patterns,这确实是Django的遗留接口。我已更新&#39;通过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