# -*- coding: utf-8 -*- from typing import Union from fastapi import Query, Depends from sqlalchemy import between from sqlalchemy.ext.asyncio import AsyncSession from crud.marktask import crud_task from models.marktask import MarkTask from models.user import Teacher from utils.depends import get_async_db, get_current_user async def analysis_line_chart(cid: str = Query("", description="班级ID"), year: Union[int, str] = Query(None, description="年份,单个或范围,范围逗号分隔,形式:开始年,结束年"), db: AsyncSession = Depends(get_async_db), current_user: Teacher = Depends(get_current_user)): _q = [] # 班级ID if (not cid) or (cid == "0"): _q.append(MarkTask.class_id.in_([int(x) for x in current_user.class_id.split(",")])) else: _q = [MarkTask.class_id == int(cid)] if isinstance(year, str): _q.append(between(MarkTask.year, *[int(x) for x in year.split(",")])) elif isinstance(year, int): _q.append(MarkTask.year == year) # 查询 _, db_tasks = await crud_task.find_all( db, filters=_q, return_fields=["name", "year", "score", "high_score", "avg_score", "low_score"]) # 组装返回结构 x = [] scores = [] high_scores = [] avg_scores = [] low_scores = [] for item in db_tasks: x.append(f"{item.name}({item.year})") scores.append(item.score) high_scores.append(item.high_score) avg_scores.append(item.avg_score) low_scores.append(item.low_score) data = { "score": { "x": x, "y": scores }, "high_score": { "x": x, "y": high_scores }, "avg_score": { "x": x, "y": avg_scores }, "low_scores": { "x": x, "y": low_scores } } return {"data": data}