分享

Django pyecharts 完成前后端分离Demo

 明灭的烟头 2020-10-06

Step 0: 新建一个 Django 项目

$ django-admin startproject pyecharts_django_demo
  • 1
  • 1

创建一个应用程序

$ python manage.py startapp demo
  • 1
  • 1

在 pyecharts_django_demo/settings.py 中注册应用程序

# pyecharts_django_demo/settings.pyINSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'demo', # <--- app 名称 'rest_framework',]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在 pyecharts_django_demo/urls.py 中新增 'demo.urls’

from django.contrib import adminfrom django.urls import pathfrom django.conf.urls import url, includeurlpatterns = [    path('admin/', admin.site.urls),    path('demo/',includ(demo.urls))]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

编辑 demo/urls.py 文件(没有就新建一个)

from django.conf.urls import urlfrom . import viewsurlpatterns = [ path('bar', views.ChartView.as_view(), name='demo'), path('index', views.IndexView, name='demo'),]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Step 2 编写画图 HTML 代码
先在根目录文件夹下新建 templates 文件夹,新建一个 index.html

sunhailindeMacBook-Pro:pyecharts_django_demo sunhailin$ ls__pycache__   db.sqlite3   demo   manage.py  pyecharts_django_demo  templates
  • 1
  • 2
  • 1
  • 2

以下为index.html代码:

<!DOCTYPE html><html><head> <meta charset='UTF-8'> <title>Awesome-pyecharts</title> <script src='https://cdn./jquery/3.0.0/jquery.min.js'></script> <script type='text/javascript' src='https://assets./assets/echarts.min.js'></script></head><body> <div id='bar' style='width:1000px; height:600px;'></div> <script> var chart = echarts.init(document.getElementById('bar'), 'white', {renderer: 'canvas'}); $( function () { fetchData(chart); } ); function fetchData() { $.ajax({ type: 'GET', url: 'http://127.0.0.1:8000/demo/bar', dataType: 'json', success: function (result) { chart.setOption(result.data); } }); } </script></body></html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

Step 3: 编写 Django 和 pyecharts 代码渲染图表
注: 目前由于 json 数据类型的问题,无法将 pyecharts 中的 JSCode 类型的数据转换成 json 数据格式返回到前端页面中使用。因此在使用前后端分离的情况下尽量避免使用 JSCode 进行画图。

将下列代码保存到 demo/views.py

import jsonfrom random import randrangefrom django.http import HttpResponsefrom rest_framework.views import APIViewfrom pyecharts.charts import Barfrom pyecharts import options as opts# Create your views here.def response_as_json(data):    json_str = json.dumps(data)    response = HttpResponse(        json_str,        content_type='application/json',    )    response['Access-Control-Allow-Origin'] = '*'    return responsedef json_response(data, code=200):    data = {        'code': code,        'msg': 'success',        'data': data,    }    return response_as_json(data)def json_error(error_string='error', code=500, **kwargs):    data = {        'code': code,        'msg': error_string,        'data': {}    }    data.update(kwargs)    return response_as_json(data)JsonResponse = json_responseJsonError = json_errordef bar_base() -> Bar:    c = (        Bar()        .add_xaxis(['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子'])        .add_yaxis('商家A', [randrange(0, 100) for _ in range(6)])        .add_yaxis('商家B', [randrange(0, 100) for _ in range(6)])        .set_global_opts(title_opts=opts.TitleOpts(title='Bar-基本示例', subtitle='我是副标题'))        .dump_options_with_quotes()    )    return cclass ChartView(APIView):    def get(self, request, *args, **kwargs):        return JsonResponse(json.loads(bar_base()))#这里对官网Demo做了修改,因为按照官网示例,我运行会报错class IndexView(request):        return HttpResponse(content=open('./templates/index.html').read())
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63

Step 4: 运行项目

$ python manage.py runserver
  • 1
  • 1

使用浏览器打开 http://127.0.0.1:8000/demo/index 即可访问服务

效果图
PS:代码引用官方文档示例,地址为:https:///#/zh-cn/web_django?id=django-%e5%89%8d%e5%90%8e%e7%ab%af%e5%88%86%e7%a6%bb

Demo下载链接:点击下载

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多