pyecharts + django 分离式调用不显示?
https://bbs.csdn.net/topics/398612805?spm=1001.2014.3001.6376
有人知道django和pyechart分离后地图不加载该怎么解决吗
和上面那个链接的问题一样
【相关推荐】
由于 json 数据类型的问题,无法将 pyecharts 中的 JSCode 类型的数据转换成 json 数据格式返回到前端页面中使用。
因此在使用前后端分离的情况下尽量避免使用 JSCode 进行画图。
将下列代码保存到 demo/views.py
中
from django.shortcuts import render
# Create your views here.
import json
from random import randrange
from django.http import HttpResponse
from rest_framework.views import APIView
from pyecharts.charts import Bar, Pie
from pyecharts.faker import Faker
from 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 response
def 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_response
JsonError = json_error
def pie_base() -> Pie:
c = (
Pie()
.add("", [list(z) for z in zip(Faker.choose(), Faker.values())])
.set_colors(["blue", "green", "yellow", "red", "pink", "orange", "purple"])
.set_global_opts(title_opts=opts.TitleOpts(title="Pie-示例"))
.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
.dump_options_with_quotes()
)
return c
class ChartView(APIView):
def get(self, request, *args, **kwargs):
return JsonResponse(json.loads(pie_base()))
class IndexView(APIView):
def get(self, request, *args, **kwargs):
return HttpResponse(content=open("./templates/index.html").read())