80 lines
2.4 KiB
Python
80 lines
2.4 KiB
Python
from fastapi import APIRouter
|
||
import pyecharts
|
||
from pyecharts import options as opts
|
||
from pyecharts.charts import Bar
|
||
from pyecharts.faker import Faker
|
||
from pyecharts.globals import CurrentConfig
|
||
import json
|
||
|
||
# 创建 APIRouter 实例
|
||
router = APIRouter(prefix="/bigscreen", tags=["大屏展示"])
|
||
|
||
# 配置使用自定义的 ECharts 路径
|
||
CurrentConfig.ONLINE_HOST = "https://gcore.jsdelivr.net/npm/echarts@6.0.0/dist/"
|
||
|
||
# 定义一个 helloWorld 路由
|
||
@router.get("/hello")
|
||
async def hello_world():
|
||
return {"message": "helloWorld"}
|
||
|
||
# 生成图表配置的函数
|
||
def generate_bar_chart_config():
|
||
c = (
|
||
Bar()
|
||
.add_xaxis(Faker.choose())
|
||
.add_yaxis("商家A", Faker.values())
|
||
.add_yaxis("商家B", Faker.values())
|
||
.set_global_opts(title_opts=opts.TitleOpts(title="Bar-MarkLine(自定义)"))
|
||
.set_series_opts(
|
||
label_opts=opts.LabelOpts(is_show=False),
|
||
markline_opts=opts.MarkLineOpts(
|
||
data=[opts.MarkLineItem(y=50, name="yAxis=50")]
|
||
),
|
||
)
|
||
)
|
||
|
||
# 获取图表的选项配置,使用 dump_options_with_quotes 方法获取可以直接序列化的选项
|
||
options_str = c.dump_options_with_quotes()
|
||
|
||
# 将字符串转换为 JSON 对象
|
||
options_json = json.loads(options_str)
|
||
|
||
return options_json
|
||
|
||
# 定义一个返回图表配置的路由
|
||
@router.get("/chart/bar")
|
||
async def get_bar_chart_config():
|
||
"""
|
||
获取柱状图配置
|
||
"""
|
||
chart_config = generate_bar_chart_config()
|
||
return chart_config
|
||
|
||
# 定义一个带有参数的路由,可以自定义图表标题
|
||
@router.get("/chart/bar/{title}")
|
||
async def get_custom_bar_chart_config(title: str):
|
||
"""
|
||
获取自定义标题的柱状图配置
|
||
"""
|
||
c = (
|
||
Bar()
|
||
.add_xaxis(Faker.choose())
|
||
.add_yaxis("商家A", Faker.values())
|
||
.add_yaxis("商家B", Faker.values())
|
||
.set_global_opts(title_opts=opts.TitleOpts(title=title))
|
||
.set_series_opts(
|
||
label_opts=opts.LabelOpts(is_show=False),
|
||
markline_opts=opts.MarkLineOpts(
|
||
data=[opts.MarkLineItem(y=50, name="yAxis=50")]
|
||
),
|
||
)
|
||
)
|
||
|
||
# 获取图表的选项配置
|
||
options_str = c.dump_options_with_quotes()
|
||
|
||
# 将字符串转换为 JSON 对象
|
||
options_json = json.loads(options_str)
|
||
|
||
return options_json
|