analysis.py 2.1 KB

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