analysis.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # -*- coding: utf-8 -*-
  2. from typing import Union
  3. from fastapi import Query, Depends
  4. from sqlalchemy import text
  5. from sqlalchemy.ext.asyncio import AsyncSession
  6. from crud.mark import crud_mark
  7. from models.user import Teacher
  8. from utils.depends import get_async_db, get_current_user
  9. async def analysis_line_chart(
  10. cid: int = Query(..., description="班级ID"),
  11. year: Union[int, str] = Query(None,
  12. description="年份,单个或范围,范围逗号分隔,形式:开始年,结束年"),
  13. db: AsyncSession = Depends(get_async_db),
  14. current_user: Teacher = Depends(get_current_user)):
  15. if year and year.isdigit():
  16. filters = {"class_id": cid, "year": year}
  17. else:
  18. filters = [
  19. text(f"class_id = {cid}"
  20. if year is None else f"class_id = {cid} AND year IN ({year})")
  21. ]
  22. # 查询
  23. _, db_tasks = await crud_mark.find_all(db,
  24. filters=filters,
  25. return_fields=[
  26. "name", "year", "score",
  27. "high_score", "avg_score",
  28. "low_score"
  29. ])
  30. # 组装返回结构
  31. x = []
  32. scores = []
  33. high_scores = []
  34. avg_scores = []
  35. low_scores = []
  36. for item in db_tasks:
  37. x.append(f"{item.name}({item.year})")
  38. scores.append(item.score)
  39. high_scores.append(item.high_score)
  40. avg_scores.append(item.avg_score)
  41. low_scores.append(item.low_score)
  42. data = {
  43. "score": {
  44. "x": x,
  45. "y": scores
  46. },
  47. "high_score": {
  48. "x": x,
  49. "y": high_scores
  50. },
  51. "avg_score": {
  52. "x": x,
  53. "y": avg_scores
  54. },
  55. "low_scores": {
  56. "x": x,
  57. "y": low_scores
  58. }
  59. }
  60. return {"data": data}