category.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  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 import text
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from common.const import RESOURCE_TYPES
  8. from crud.base import CrudManager
  9. from crud.resource import crud_work_category, crud_exam_category
  10. from models.user import SysUser, Student, Teacher
  11. from utils.depends import get_async_db, get_current_user
  12. # 分类
  13. async def get_category_tree(crud: CrudManager,
  14. db: AsyncSession = Depends(get_async_db),
  15. root: List[Any] = None):
  16. for item in root:
  17. children = await crud.fetch_all(db, filters=[text(f"pid={item.id}")])
  18. item.children = children
  19. await get_category_tree(crud, db, item.children)
  20. async def get_categories(
  21. 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. crud = crud_work_category if ctype == "work" else crud_exam_category
  27. root = await crud.fetch_all(db, filters=[text("pid = 0")])
  28. await get_category_tree(crud, db, root)
  29. return {"data": root}