category.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from typing import Any, List, Union
  4. from fastapi import Depends, Query
  5. from sqlalchemy.ext.asyncio import AsyncSession
  6. from common.const import RESOURCE_TYPES
  7. from crud.base import CrudManager
  8. from crud.resource import CATEGORY_CRUDS
  9. from models.resource import WorkResource, ExamResource, CATEGORY_MODES
  10. from models.user import Student, Teacher
  11. from utils.depends import get_async_db, get_current_user
  12. # 分类
  13. async def get_category_tree(crud: CrudManager,
  14. model: Union[WorkResource, ExamResource],
  15. db: AsyncSession = Depends(get_async_db),
  16. root: List[Any] = None):
  17. for item in root:
  18. children = await crud.fetch_all(db, filters=[model.pid == item.id])
  19. item.children = children
  20. await get_category_tree(crud, model, db, item.children)
  21. async def get_categories(ctype: str = Query(..., description="资源类型,exam / work"),
  22. db: AsyncSession = Depends(get_async_db),
  23. current_user: Union[Teacher, Student] = Depends(get_current_user)):
  24. if ctype not in RESOURCE_TYPES:
  25. return {"errcode": 400, "mess": "资源类型错误!"}
  26. else:
  27. crud = CATEGORY_CRUDS[ctype]
  28. model = CATEGORY_MODES[ctype]
  29. root = await crud.fetch_all(db, filters=[model.pid == 0])
  30. await get_category_tree(crud, model, db, root)
  31. return {"data": root}