Download app/routers/user/category.py from binhugg2/api: direct link, hf CLI and curl.
- Browser
- Download file 1.77 kB
-
https://huggingface.co/spaces/binhugg2/api/resolve/main/app/routers/user/category.py
- Command line
-
hf download hf://spaces/binhugg2/api/app/routers/user/category.py
-
curl -L -o category.py https://huggingface.co/spaces/binhugg2/api/resolve/main/app/routers/user/category.py
1.77 kB
| from fastapi import APIRouter, Depends | |
| from sqlalchemy import select | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from app.cache import cache_get, cache_set, category_tree_key | |
| from app.config import settings | |
| from app.database import get_db | |
| from app.models.category import Category | |
| from app.schemas.common import ApiResponse | |
| from app.schemas.user.category import CategoryUserNode | |
| router = APIRouter() | |
| async def list_categories(db: AsyncSession = Depends(get_db)): | |
| cache_key = category_tree_key() | |
| cached = await cache_get(cache_key) | |
| if cached is not None: | |
| return ApiResponse.ok(cached) | |
| result = await db.execute( | |
| select(Category) | |
| .where(Category.is_active == True) | |
| .order_by(Category.sort_order) | |
| ) | |
| all_cats = result.scalars().all() | |
| cat_map: dict[int, CategoryUserNode] = {} | |
| for c in all_cats: | |
| cat_map[c.id] = CategoryUserNode(id=c.id, name=c.name, children=[]) | |
| roots: list[CategoryUserNode] = [] | |
| for c in all_cats: | |
| node = cat_map[c.id] | |
| if c.parent_id and c.parent_id in cat_map: | |
| parent = cat_map[c.parent_id] | |
| if parent.children is None: | |
| parent.children = [] | |
| parent.children.append(node) | |
| else: | |
| roots.append(node) | |
| for node in roots: | |
| _clean_empty_children(node) | |
| data = [r.model_dump() for r in roots] | |
| await cache_set(cache_key, data, settings.CACHE_TTL_CATEGORY) | |
| return ApiResponse.ok(data) | |
| def _clean_empty_children(node: CategoryUserNode): | |
| if node.children is not None: | |
| for child in node.children: | |
| _clean_empty_children(child) | |
| if len(node.children) == 0: | |
| node.children = None | |