如何在Django Web应用程序中渲染Matplotlib图? [英] How to render a Matplotlib plot in a Django web application?

查看:213
本文介绍了如何在Django Web应用程序中渲染Matplotlib图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读


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).

解决方案

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:

这篇关于如何在Django Web应用程序中渲染Matplotlib图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆