release: Elysia ToDo v1.0.0
鍏ㄦ爤涓汉淇℃伅绠$悊搴旂敤锛岄泦鎴愬緟鍔炰换鍔°€佷範鎯墦鍗°€佺邯蹇垫棩鎻愰啋銆佽祫浜ф€昏鍔熻兘銆 Made-with: Cursor
This commit is contained in:
34
api/app/utils/crud.py
Normal file
34
api/app/utils/crud.py
Normal file
@@ -0,0 +1,34 @@
|
||||
"""
|
||||
通用 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
|
||||
Reference in New Issue
Block a user