35 lines
803 B
Python
35 lines
803 B
Python
"""
|
|
通用 CRUD 工具函数
|
|
"""
|
|
from typing import Type, TypeVar
|
|
from fastapi import HTTPException
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.database import Base
|
|
from app.utils.logger import logger
|
|
|
|
|
|
ModelType = TypeVar("ModelType", bound=Base)
|
|
|
|
|
|
def get_or_404(
|
|
db: Session,
|
|
model: Type[ModelType],
|
|
item_id: int,
|
|
name: str = "资源"
|
|
) -> ModelType:
|
|
"""
|
|
获取实体,不存在时抛出 404 异常
|
|
|
|
Args:
|
|
db: 数据库会话
|
|
model: 模型类
|
|
item_id: 实体 ID
|
|
name: 实体名称(用于错误信息)
|
|
"""
|
|
item = db.query(model).filter(model.id == item_id).first()
|
|
if not item:
|
|
logger.warning(f"{name}不存在: id={item_id}")
|
|
raise HTTPException(status_code=404, detail=f"{name}不存在")
|
|
return item
|