Django前端展示后端现场画出来的Matplotlib图像

整个流程比较简单:

定义View

首先在view.py文件中:

import matplotlib.pyplot as plt
from io import StringIO
from django.shortcuts import render
from django.views.generic import View


def return_graph():
    plt.clf()  # 清空图像
    x = [1, 2, 3, 4, 5]
    y = [1, 4, 9, 16, 25]
    fig = plt.figure()
    plt.plot(x, y)
    img_stringio = StringIO()
    fig.savefig(img_stringio, format='svg')
    img_stringio.seek(0)
    data = img_stringio.getvalue()
    return data


class ShowMatplotlibView(View):
    def get(self, request):
        graph = return_graph()
        context = {}
        context['graph'] = graph  # 这个graph其实是一段包含了html,css的xml格式数据
        return render(request, "show_pic.html", context=context)

其中return_graph()函数是用来打包图像的,通过ShowMatplotlibViewget()方法就可以得到需要的图像了

定义URL

然后我们定义路由(这里根据自己的项目定义哈):

from django.urls import path
from .views import ShowMatplotlibView

urlpatterns = [
    path("show_pic/", ShowMatplotlibView.as_view()),
]

前端页面

最后新建一个页面,叫show_pic.html(这个页面要与上面view.pyrender()函数对应),比如:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{ graph | safe }}
</body>
</html>

然后访问:http://127.0.0.1:8000/show_pic,就可以得到想要的结果图:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呆萌的代Ma

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值