Files
2026-06-25 17:41:06 +08:00

86 lines
2.7 KiB
Mako

<%
# 对 entity 中的 name 进行大小写处理,生成模型名、路由名和模式名
model_name = entity.name.capitalize()
endpoint = entity.name.lower()
router_name = endpoint + '_router'
schema_name = model_name + 'Schema'
# 处理实体关系
relations = generator._process_relations(entity) if hasattr(generator, '_process_relations') else []
%>
# 导入必要的模块和类
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
# 导入数据库会话依赖和相关模型、模式
from ..database import get_db
from ..models.${endpoint} import ${model_name}
from ..schemas.${endpoint} import ${schema_name}, ${model_name}Create, ${model_name}Update
# 创建 APIRouter 实例
${router_name} = APIRouter(
prefix="/api/${endpoint}s",
tags=["${model_name}管理"],
# 根据配置添加依赖项
% if hasattr(entity, 'api') and hasattr(entity.api, 'auth_required') and entity.api.auth_required:
dependencies=[Depends(get_current_active_user)],
% endif
)
# 定义获取实体列表的路由
@${router_name}.get("/", response_model=List[${schema_name}])
def list_${endpoint}s(
skip: int = 0,
limit: int = 100,
db: Session = Depends(get_db)
):
"""
获取${model_name}列表
- **skip**: 跳过多少条记录
- **limit**: 返回最多多少条记录
"""
return db.query(${model_name}).offset(skip).limit(limit).all()
# 定义创建新实体的路由
@${router_name}.post("/", response_model=${schema_name})
def create_${endpoint}(
${endpoint}: ${model_name}Create,
db: Session = Depends(get_db)
% if hasattr(entity, 'api') and hasattr(entity.api, 'auth_required') and entity.api.auth_required:
, current_user: User = Depends(get_current_active_user)
% endif
):
"""
创建新的${model_name}
"""
db_${endpoint} = ${model_name}(**${endpoint}.dict())
db.add(db_${endpoint})
db.commit()
db.refresh(db_${endpoint})
return db_${endpoint}
# 其他 CRUD 操作...
% for rel in relations:
# 定义获取实体关联关系的路由
@${router_name}.get(
"/{${endpoint}_id}/${rel['name']}",
response_model=
% if rel['type'] in ('one-to-many', 'many-to-many'):
List[${rel['target'].capitalize()}Schema]
% else:
${rel['target'].capitalize()}Schema
% endif
)
def get_${endpoint}_${rel['name']}(
${endpoint}_id: int,
db: Session = Depends(get_db)
):
"""
获取${model_name}${rel['name']}
"""
entity_obj = db.query(${model_name}).get(${endpoint}_id)
if not entity_obj:
raise HTTPException(status_code=404, detail="${model_name} not found")
return entity_obj.${rel['name']}
% endfor