mirror of
https://github.com/fastapiadmin/FastapiAdmin.git
synced 2026-09-21 04:46:26 +00:00
feat: 重构代码生成模块并优化相关功能
- 重构代码生成模板,统一路由前缀和业务路径规范 - 优化数据库表分页查询性能,支持方言特定实现 - 新增同步数据库差异预览功能 - 调整字段配置界面,支持拖拽排序和批量设置 - 清理旧版示例代码和冗余配置 - 修复权限和路由嵌套路径处理问题 - 优化前端样式和交互细节
This commit is contained in:
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
import urllib.parse
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Path, UploadFile
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
|
||||
from app.api.v1.module_system.auth.schema import AuthSchema
|
||||
from app.common.response import ResponseSchema, StreamResponse, SuccessResponse
|
||||
from app.core.base_params import PaginationQueryParam
|
||||
from app.core.base_schema import BatchSetAvailable
|
||||
from app.core.dependencies import AuthPermission
|
||||
from app.core.logger import log
|
||||
from app.core.router_class import OperationLogRoute
|
||||
from app.utils.common_util import bytes2file_response
|
||||
|
||||
from .schema import Demo01CreateSchema, Demo01OutSchema, Demo01QueryParam, Demo01UpdateSchema
|
||||
from .service import Demo01Service
|
||||
|
||||
Demo01Router = APIRouter(route_class=OperationLogRoute, prefix="/demo01", tags=["示例01模块"])
|
||||
|
||||
|
||||
@Demo01Router.get(
|
||||
"/detail/{id}",
|
||||
summary="获取示例01详情",
|
||||
description="获取示例01详情",
|
||||
response_model=ResponseSchema[Demo01OutSchema],
|
||||
)
|
||||
async def get_obj_detail_controller(
|
||||
id: Annotated[int, Path(description="示例ID")],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_example:demo01:detail"]))],
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
获取示例01详情
|
||||
|
||||
参数:
|
||||
- id (int): 示例01ID
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
返回:
|
||||
- JSONResponse: 包含示例01详情的JSON响应
|
||||
"""
|
||||
result_dict = await Demo01Service.detail_service(id=id, auth=auth)
|
||||
log.info(f"获取示例01详情成功 {id}")
|
||||
return SuccessResponse(data=result_dict, msg="获取示例01详情成功")
|
||||
|
||||
|
||||
@Demo01Router.get(
|
||||
"/list",
|
||||
summary="查询示例01列表",
|
||||
description="查询示例01列表",
|
||||
response_model=ResponseSchema[list[Demo01OutSchema]],
|
||||
)
|
||||
async def get_obj_list_controller(
|
||||
page: Annotated[PaginationQueryParam, Depends()],
|
||||
search: Annotated[Demo01QueryParam, Depends()],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_example:demo01:query"]))],
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
查询示例01列表
|
||||
|
||||
参数:
|
||||
- page (PaginationQueryParam): 分页查询参数
|
||||
- search (Demo01QueryParam): 查询参数
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
返回:
|
||||
- JSONResponse: 包含示例01列表分页信息的JSON响应
|
||||
"""
|
||||
# 使用数据库分页而不是应用层分页
|
||||
result_dict = await Demo01Service.page_service(
|
||||
auth=auth,
|
||||
page_no=page.page_no,
|
||||
page_size=page.page_size,
|
||||
search=search,
|
||||
order_by=page.order_by,
|
||||
)
|
||||
log.info("查询示例01列表成功")
|
||||
return SuccessResponse(data=result_dict, msg="查询示例01列表成功")
|
||||
|
||||
|
||||
@Demo01Router.post(
|
||||
"/create",
|
||||
summary="创建示例01",
|
||||
description="创建示例01",
|
||||
response_model=ResponseSchema[Demo01OutSchema],
|
||||
)
|
||||
async def create_obj_controller(
|
||||
data: Demo01CreateSchema,
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_example:demo01:create"]))],
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
创建示例01
|
||||
|
||||
参数:
|
||||
- data (DemoCreateSchema): 示例创建模型
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
返回:
|
||||
- JSONResponse: 包含创建示例01详情的JSON响应
|
||||
"""
|
||||
result_dict = await Demo01Service.create_service(auth=auth, data=data)
|
||||
log.info(f"创建示例01成功: {result_dict.get('name')}")
|
||||
return SuccessResponse(data=result_dict, msg="创建示例01成功")
|
||||
|
||||
|
||||
@Demo01Router.put(
|
||||
"/update/{id}",
|
||||
summary="修改示例01",
|
||||
description="修改示例01",
|
||||
response_model=ResponseSchema[Demo01OutSchema],
|
||||
)
|
||||
async def update_obj_controller(
|
||||
data: Demo01UpdateSchema,
|
||||
id: Annotated[int, Path(description="示例ID")],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_example:demo01:update"]))],
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
修改示例01
|
||||
|
||||
参数:
|
||||
- data (Demo01UpdateSchema): 示例01更新模型
|
||||
- id (int): 示例ID
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
返回:
|
||||
- JSONResponse: 包含修改示例01详情的JSON响应
|
||||
"""
|
||||
result_dict = await Demo01Service.update_service(auth=auth, id=id, data=data)
|
||||
log.info(f"修改示例01成功: {result_dict.get('name')}")
|
||||
return SuccessResponse(data=result_dict, msg="修改示例01成功")
|
||||
|
||||
|
||||
@Demo01Router.delete(
|
||||
"/delete",
|
||||
summary="删除示例01",
|
||||
description="删除示例01",
|
||||
response_model=ResponseSchema[None],
|
||||
)
|
||||
async def delete_obj_controller(
|
||||
ids: Annotated[list[int], Body(description="ID列表")],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_example:demo01:delete"]))],
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
删除示例01
|
||||
|
||||
参数:
|
||||
- ids (list[int]): 示例ID列表
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
返回:
|
||||
- JSONResponse: 包含删除示例01详情的JSON响应
|
||||
"""
|
||||
await Demo01Service.delete_service(auth=auth, ids=ids)
|
||||
log.info(f"删除示例01成功: {ids}")
|
||||
return SuccessResponse(msg="删除示例01成功")
|
||||
|
||||
|
||||
@Demo01Router.patch(
|
||||
"/available/setting",
|
||||
summary="批量修改示例01状态",
|
||||
description="批量修改示例01状态",
|
||||
response_model=ResponseSchema[None],
|
||||
)
|
||||
async def batch_set_available_obj_controller(
|
||||
data: BatchSetAvailable,
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_example:demo01:patch"]))],
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
批量修改示例01状态
|
||||
|
||||
参数:
|
||||
- data (BatchSetAvailable): 批量修改示例01状态模型
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
返回:
|
||||
- JSONResponse: 包含批量修改示例01状态详情的JSON响应
|
||||
"""
|
||||
await Demo01Service.set_available_service(auth=auth, data=data)
|
||||
log.info(f"批量修改示例01状态成功: {data.ids}")
|
||||
return SuccessResponse(msg="批量修改示例01状态成功")
|
||||
|
||||
|
||||
@Demo01Router.post(
|
||||
"/export",
|
||||
summary="导出示例01",
|
||||
description="导出示例01",
|
||||
)
|
||||
async def export_obj_list_controller(
|
||||
search: Annotated[Demo01QueryParam, Depends()],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_example:demo01:export"]))],
|
||||
) -> StreamingResponse:
|
||||
"""
|
||||
导出示例01
|
||||
|
||||
参数:
|
||||
- search (Demo01QueryParam): 查询参数
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
返回:
|
||||
- StreamingResponse: 包含示例01列表的Excel文件流响应
|
||||
"""
|
||||
result_dict_list = await Demo01Service.list_service(search=search, auth=auth)
|
||||
export_result = await Demo01Service.batch_export_service(obj_list=result_dict_list)
|
||||
log.info("导出示例01成功")
|
||||
|
||||
return StreamResponse(
|
||||
data=bytes2file_response(export_result),
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": "attachment; filename=demo01.xlsx"},
|
||||
)
|
||||
|
||||
|
||||
@Demo01Router.post(
|
||||
"/import",
|
||||
summary="导入示例01",
|
||||
description="导入示例01",
|
||||
response_model=ResponseSchema[str],
|
||||
)
|
||||
async def import_obj_list_controller(
|
||||
file: UploadFile,
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_example:demo01:import"]))],
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
导入示例01
|
||||
|
||||
参数:
|
||||
- file (UploadFile): 导入的Excel文件
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
返回:
|
||||
- JSONResponse: 包含导入示例详情的JSON响应
|
||||
"""
|
||||
batch_import_result = await Demo01Service.batch_import_service(
|
||||
file=file, auth=auth, update_support=True
|
||||
)
|
||||
log.info(f"导入示例01成功: {batch_import_result}")
|
||||
return SuccessResponse(data=batch_import_result, msg="导入示例01成功")
|
||||
|
||||
|
||||
@Demo01Router.post(
|
||||
"/download/template",
|
||||
summary="获取示例01导入模板",
|
||||
description="获取示例01导入模板",
|
||||
dependencies=[Depends(AuthPermission(["module_example:demo01:download"]))],
|
||||
)
|
||||
async def export_obj_template_controller() -> StreamingResponse:
|
||||
"""
|
||||
获取示例01导入模板
|
||||
|
||||
返回:
|
||||
- StreamingResponse: 包含示例01导入模板的Excel文件流响应
|
||||
"""
|
||||
import_template_result = await Demo01Service.import_template_download_service()
|
||||
log.info("获取示例01导入模板成功")
|
||||
|
||||
return StreamResponse(
|
||||
data=bytes2file_response(import_template_result),
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={
|
||||
"Content-Disposition": f"attachment; filename={urllib.parse.quote('示例01导入模板.xlsx')}",
|
||||
"Access-Control-Expose-Headers": "Content-Disposition",
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,135 @@
|
||||
from collections.abc import Sequence
|
||||
|
||||
from app.api.v1.module_system.auth.schema import AuthSchema
|
||||
from app.core.base_crud import CRUDBase
|
||||
|
||||
from .model import Demo01Model
|
||||
from .schema import Demo01CreateSchema, Demo01OutSchema, Demo01UpdateSchema
|
||||
|
||||
|
||||
class Demo01CRUD(CRUDBase[Demo01Model, Demo01CreateSchema, Demo01UpdateSchema]):
|
||||
"""示例数据层"""
|
||||
|
||||
def __init__(self, auth: AuthSchema) -> None:
|
||||
"""
|
||||
初始化CRUD数据层
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
"""
|
||||
super().__init__(model=Demo01Model, auth=auth)
|
||||
|
||||
async def get_by_id_crud(self, id: int, preload: list[str] | None = None) -> Demo01Model | None:
|
||||
"""
|
||||
详情
|
||||
|
||||
参数:
|
||||
- id (int): 示例ID
|
||||
- preload (list[str] | None): 预加载关系,未提供时使用模型默认项
|
||||
|
||||
返回:
|
||||
- Demo01Model | None: 示例模型实例或None
|
||||
"""
|
||||
return await self.get(id=id, preload=preload)
|
||||
|
||||
async def list_crud(
|
||||
self,
|
||||
search: dict | None = None,
|
||||
order_by: list[dict] | None = None,
|
||||
preload: list[str] | None = None,
|
||||
) -> Sequence[Demo01Model]:
|
||||
"""
|
||||
列表查询
|
||||
|
||||
参数:
|
||||
- search (dict | None): 查询参数
|
||||
- order_by (list[dict] | None): 排序参数
|
||||
- preload (list[str] | None): 预加载关系,未提供时使用模型默认项
|
||||
|
||||
返回:
|
||||
- Sequence[Demo01Model]: 示例模型实例序列
|
||||
"""
|
||||
return await self.list(search=search, order_by=order_by, preload=preload)
|
||||
|
||||
async def create_crud(self, data: Demo01CreateSchema) -> Demo01Model | None:
|
||||
"""
|
||||
创建
|
||||
|
||||
参数:
|
||||
- data (Demo01CreateSchema): 示例创建模型
|
||||
|
||||
返回:
|
||||
- Demo01Model | None: 示例模型实例或None
|
||||
"""
|
||||
return await self.create(data=data)
|
||||
|
||||
async def update_crud(self, id: int, data: Demo01UpdateSchema) -> Demo01Model | None:
|
||||
"""
|
||||
更新
|
||||
|
||||
参数:
|
||||
- id (int): 示例ID
|
||||
- data (Demo01UpdateSchema): 示例更新模型
|
||||
|
||||
返回:
|
||||
- Demo01Model | None: 示例模型实例或None
|
||||
"""
|
||||
return await self.update(id=id, data=data)
|
||||
|
||||
async def delete_crud(self, ids: list[int]) -> None:
|
||||
"""
|
||||
批量删除
|
||||
|
||||
参数:
|
||||
- ids (List[int]): 示例ID列表
|
||||
|
||||
返回:
|
||||
- None
|
||||
"""
|
||||
return await self.delete(ids=ids)
|
||||
|
||||
async def set_available_crud(self, ids: list[int], status: str) -> None:
|
||||
"""
|
||||
批量设置可用状态
|
||||
|
||||
参数:
|
||||
- ids (list[int]): 示例ID列表
|
||||
- status (str): 可用状态
|
||||
|
||||
返回:
|
||||
- None
|
||||
"""
|
||||
return await self.set(ids=ids, status=status)
|
||||
|
||||
async def page_crud(
|
||||
self,
|
||||
offset: int,
|
||||
limit: int,
|
||||
order_by: list[dict] | None = None,
|
||||
search: dict | None = None,
|
||||
preload: list | None = None,
|
||||
) -> dict:
|
||||
"""
|
||||
分页查询
|
||||
|
||||
参数:
|
||||
- offset (int): 偏移量
|
||||
- limit (int): 每页数量
|
||||
- order_by (list[dict] | None): 排序参数
|
||||
- search (dict | None): 查询参数
|
||||
- preload (list | None): 预加载关系,未提供时使用模型默认项
|
||||
|
||||
返回:
|
||||
- dict: 分页数据
|
||||
"""
|
||||
order_by_list = order_by or [{"id": "asc"}]
|
||||
search_dict = search or {}
|
||||
|
||||
return await self.page(
|
||||
offset=offset,
|
||||
limit=limit,
|
||||
order_by=order_by_list,
|
||||
search=search_dict,
|
||||
out_schema=Demo01OutSchema,
|
||||
preload=preload,
|
||||
)
|
||||
@@ -0,0 +1,18 @@
|
||||
|
||||
from sqlalchemy import String
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.core.base_model import ModelMixin, UserMixin
|
||||
|
||||
|
||||
class Demo01Model(ModelMixin, UserMixin):
|
||||
"""
|
||||
示例表 - 涵盖大多数常用数据类型
|
||||
"""
|
||||
|
||||
__tablename__: str = "gen_demo01"
|
||||
__table_args__: dict[str, str] = {"comment": "示例1表"}
|
||||
__loader_options__: list[str] = ["created_by", "updated_by"]
|
||||
|
||||
# 字符串类型
|
||||
name: Mapped[str] = mapped_column(String(64), nullable=False, comment="名称")
|
||||
@@ -0,0 +1,105 @@
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
from fastapi import Query
|
||||
from pydantic import (
|
||||
BaseModel,
|
||||
ConfigDict,
|
||||
Field,
|
||||
field_validator,
|
||||
model_validator,
|
||||
)
|
||||
|
||||
from app.common.enums import QueueEnum
|
||||
from app.core.base_schema import BaseSchema, UserBySchema
|
||||
from app.core.validator import DateTimeStr
|
||||
|
||||
|
||||
class Demo01CreateSchema(BaseModel):
|
||||
"""新增模型"""
|
||||
|
||||
name: str = Field(..., description="名称")
|
||||
status: str = Field(default="0", description="是否启用(0:启用 1:禁用)")
|
||||
description: str | None = Field(default=None, description="描述")
|
||||
|
||||
@field_validator("name")
|
||||
@classmethod
|
||||
def validate_name(cls, v: str) -> str:
|
||||
"""验证名称字段的格式和内容"""
|
||||
# 去除首尾空格
|
||||
v = v.strip()
|
||||
if not v:
|
||||
raise ValueError("名称不能为空")
|
||||
return v
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _after_validation(self):
|
||||
"""
|
||||
核心业务规则校验
|
||||
"""
|
||||
# 长度校验:名称最小长度
|
||||
if len(self.name) < 2 or len(self.name) > 50:
|
||||
raise ValueError("名称长度必须在2-50个字符之间")
|
||||
# 格式校验:名称只能包含字母、数字、下划线和中划线
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]+", self.name):
|
||||
raise ValueError("名称只能包含字母、数字、下划线和中划线")
|
||||
if self.status not in ["0", "1"]:
|
||||
raise ValueError("是否启用必须为0或1")
|
||||
# 描述校验:描述最大长度
|
||||
if self.description and len(self.description) > 255:
|
||||
raise ValueError("描述长度不能超过255个字符")
|
||||
return self
|
||||
|
||||
|
||||
class Demo01UpdateSchema(Demo01CreateSchema):
|
||||
"""更新模型"""
|
||||
|
||||
|
||||
class Demo01OutSchema(Demo01CreateSchema, BaseSchema, UserBySchema):
|
||||
"""响应模型"""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Demo01QueryParam:
|
||||
"""示例查询参数"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str | None = Query(None, description="名称"),
|
||||
description: str | None = Query(None, description="描述"),
|
||||
status: str | None = Query(None, description="是否启用"),
|
||||
created_time: list[DateTimeStr] | None = Query(
|
||||
None,
|
||||
description="创建时间范围",
|
||||
examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"],
|
||||
),
|
||||
updated_time: list[DateTimeStr] | None = Query(
|
||||
None,
|
||||
description="更新时间范围",
|
||||
examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"],
|
||||
),
|
||||
created_id: int | None = Query(None, description="创建人"),
|
||||
updated_id: int | None = Query(None, description="更新人"),
|
||||
) -> None:
|
||||
# 模糊查询字段
|
||||
self.name = (QueueEnum.like.value, name)
|
||||
if description:
|
||||
self.description = (QueueEnum.like.value, description)
|
||||
|
||||
# 精确查询字段
|
||||
if status:
|
||||
self.status = (QueueEnum.eq.value, status)
|
||||
|
||||
# 时间范围查询
|
||||
if created_time and len(created_time) == 2:
|
||||
self.created_time = (QueueEnum.between.value, (created_time[0], created_time[1]))
|
||||
if updated_time and len(updated_time) == 2:
|
||||
self.updated_time = (QueueEnum.between.value, (updated_time[0], updated_time[1]))
|
||||
|
||||
# 关联查询字段
|
||||
if created_id:
|
||||
self.created_id = (QueueEnum.eq.value, created_id)
|
||||
if updated_id:
|
||||
self.updated_id = (QueueEnum.eq.value, updated_id)
|
||||
@@ -0,0 +1,326 @@
|
||||
import io
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
from fastapi import UploadFile
|
||||
|
||||
from app.api.v1.module_system.auth.schema import AuthSchema
|
||||
from app.core.base_schema import BatchSetAvailable
|
||||
from app.core.exceptions import CustomException
|
||||
from app.core.logger import log
|
||||
from app.utils.excel_util import ExcelUtil
|
||||
|
||||
from .crud import Demo01CRUD
|
||||
from .schema import (
|
||||
Demo01CreateSchema,
|
||||
Demo01OutSchema,
|
||||
Demo01QueryParam,
|
||||
Demo01UpdateSchema,
|
||||
)
|
||||
|
||||
|
||||
class Demo01Service:
|
||||
"""
|
||||
示例管理模块服务层
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
async def detail_service(cls, auth: AuthSchema, id: int) -> dict:
|
||||
"""
|
||||
详情
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- id (int): 示例ID
|
||||
|
||||
返回:
|
||||
- dict: 示例模型实例字典
|
||||
"""
|
||||
obj = await Demo01CRUD(auth).get_by_id_crud(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg="该数据不存在")
|
||||
return Demo01OutSchema.model_validate(obj).model_dump()
|
||||
|
||||
@classmethod
|
||||
async def list_service(
|
||||
cls,
|
||||
auth: AuthSchema,
|
||||
search: Demo01QueryParam | None = None,
|
||||
order_by: list[dict[str, str]] | None = None,
|
||||
) -> list[dict]:
|
||||
"""
|
||||
列表查询
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- search (Demo01QueryParam | None): 查询参数
|
||||
- order_by (list[dict[str, str]] | None): 排序参数
|
||||
|
||||
返回:
|
||||
- list[dict]: 示例模型实例字典列表
|
||||
"""
|
||||
search_dict = search.__dict__ if search else None
|
||||
obj_list = await Demo01CRUD(auth).list_crud(search=search_dict, order_by=order_by)
|
||||
return [Demo01OutSchema.model_validate(obj).model_dump() for obj in obj_list]
|
||||
|
||||
@classmethod
|
||||
async def page_service(
|
||||
cls,
|
||||
auth: AuthSchema,
|
||||
page_no: int,
|
||||
page_size: int,
|
||||
search: Demo01QueryParam | None = None,
|
||||
order_by: list[dict[str, str]] | None = None,
|
||||
) -> dict:
|
||||
"""
|
||||
分页查询
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- page_no (int): 页码
|
||||
- page_size (int): 每页数量
|
||||
- search (Demo01QueryParam | None): 查询参数
|
||||
- order_by (list[dict[str, str]] | None): 排序参数
|
||||
|
||||
返回:
|
||||
- dict: 分页数据
|
||||
"""
|
||||
search_dict = search.__dict__ if search else {}
|
||||
order_by_list = order_by or [{"id": "asc"}]
|
||||
offset = (page_no - 1) * page_size
|
||||
|
||||
result = await Demo01CRUD(auth).page_crud(
|
||||
offset=offset,
|
||||
limit=page_size,
|
||||
order_by=order_by_list,
|
||||
search=search_dict,
|
||||
)
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
async def create_service(cls, auth: AuthSchema, data: Demo01CreateSchema) -> dict:
|
||||
"""
|
||||
创建
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- data (Demo01CreateSchema): 示例创建模型
|
||||
|
||||
返回:
|
||||
- dict: 示例模型实例字典
|
||||
"""
|
||||
obj = await Demo01CRUD(auth).get(name=data.name)
|
||||
if obj:
|
||||
raise CustomException(msg="创建失败,名称已存在")
|
||||
obj = await Demo01CRUD(auth).create_crud(data=data)
|
||||
return Demo01OutSchema.model_validate(obj).model_dump()
|
||||
|
||||
@classmethod
|
||||
async def update_service(cls, auth: AuthSchema, id: int, data: Demo01UpdateSchema) -> dict:
|
||||
"""
|
||||
更新
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- id (int): 示例ID
|
||||
- data (Demo01UpdateSchema): 示例更新模型
|
||||
|
||||
返回:
|
||||
- dict: 示例模型实例字典
|
||||
"""
|
||||
# 检查数据是否存在
|
||||
obj = await Demo01CRUD(auth).get_by_id_crud(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg="更新失败,该数据不存在")
|
||||
|
||||
# 检查名称是否重复
|
||||
exist_obj = await Demo01CRUD(auth).get(name=data.name)
|
||||
if exist_obj and exist_obj.id != id:
|
||||
raise CustomException(msg="更新失败,名称重复")
|
||||
|
||||
obj = await Demo01CRUD(auth).update_crud(id=id, data=data)
|
||||
return Demo01OutSchema.model_validate(obj).model_dump()
|
||||
|
||||
@classmethod
|
||||
async def delete_service(cls, auth: AuthSchema, ids: list[int]) -> None:
|
||||
"""
|
||||
删除
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- ids (list[int]): 示例ID列表
|
||||
|
||||
返回:
|
||||
- None
|
||||
"""
|
||||
if len(ids) < 1:
|
||||
raise CustomException(msg="删除失败,删除对象不能为空")
|
||||
|
||||
# 检查所有要删除的数据是否存在
|
||||
for id in ids:
|
||||
obj = await Demo01CRUD(auth).get_by_id_crud(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg=f"删除失败,ID为{id}的数据不存在")
|
||||
|
||||
await Demo01CRUD(auth).delete_crud(ids=ids)
|
||||
|
||||
@classmethod
|
||||
async def set_available_service(cls, auth: AuthSchema, data: BatchSetAvailable) -> None:
|
||||
"""
|
||||
批量设置状态
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- data (BatchSetAvailable): 批量设置状态模型
|
||||
|
||||
返回:
|
||||
- None
|
||||
"""
|
||||
await Demo01CRUD(auth).set_available_crud(ids=data.ids, status=data.status)
|
||||
|
||||
@classmethod
|
||||
async def batch_export_service(cls, obj_list: list[dict[str, Any]]) -> bytes:
|
||||
"""
|
||||
批量导出
|
||||
|
||||
参数:
|
||||
- obj_list (list[dict[str, Any]]): 示例模型实例字典列表
|
||||
|
||||
返回:
|
||||
- bytes: Excel文件字节流
|
||||
"""
|
||||
mapping_dict = {
|
||||
"id": "编号",
|
||||
"name": "名称",
|
||||
"status": "状态",
|
||||
"description": "备注",
|
||||
"created_time": "创建时间",
|
||||
"updated_time": "更新时间",
|
||||
"created_id": "创建者",
|
||||
}
|
||||
|
||||
# 复制数据并转换状态
|
||||
data = obj_list.copy()
|
||||
for item in data:
|
||||
# 处理状态
|
||||
item["status"] = "启用" if item.get("status") == "0" else "停用"
|
||||
# 处理创建者
|
||||
creator_info = item.get("created_id")
|
||||
if isinstance(creator_info, dict):
|
||||
item["created_id"] = creator_info.get("name", "未知")
|
||||
else:
|
||||
item["created_id"] = "未知"
|
||||
|
||||
return ExcelUtil.export_list2excel(list_data=data, mapping_dict=mapping_dict)
|
||||
|
||||
@classmethod
|
||||
async def batch_import_service(
|
||||
cls, auth: AuthSchema, file: UploadFile, update_support: bool = False
|
||||
) -> str:
|
||||
"""
|
||||
批量导入
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- file (UploadFile): 上传的Excel文件
|
||||
- update_support (bool): 是否支持更新存在数据
|
||||
|
||||
返回:
|
||||
- str: 导入结果信息
|
||||
"""
|
||||
|
||||
header_dict = {"名称": "name", "状态": "status", "描述": "description"}
|
||||
|
||||
try:
|
||||
# 读取Excel文件
|
||||
contents = await file.read()
|
||||
df = pd.read_excel(io.BytesIO(contents))
|
||||
await file.close()
|
||||
|
||||
if df.empty:
|
||||
raise CustomException(msg="导入文件为空")
|
||||
|
||||
# 检查表头是否完整
|
||||
missing_headers = [header for header in header_dict.keys() if header not in df.columns]
|
||||
if missing_headers:
|
||||
raise CustomException(msg=f"导入文件缺少必要的列: {', '.join(missing_headers)}")
|
||||
|
||||
# 重命名列名
|
||||
df.rename(columns=header_dict, inplace=True)
|
||||
|
||||
# 验证必填字段
|
||||
required_fields = ["name", "status"]
|
||||
errors = []
|
||||
for field in required_fields:
|
||||
missing_rows = df[df[field].isnull()].index.tolist()
|
||||
if missing_rows:
|
||||
field_name = next(k for k, v in header_dict.items() if v == field)
|
||||
rows_str = "、".join([str(i + 1) for i in missing_rows])
|
||||
errors.append(f"{field_name}不能为空,第{rows_str}行")
|
||||
if errors:
|
||||
raise CustomException(msg=f"导入失败,以下行缺少必要字段:\n{'; '.join(errors)}")
|
||||
|
||||
error_msgs = []
|
||||
success_count = 0
|
||||
count = 0
|
||||
|
||||
# 处理每一行数据
|
||||
for _index, row in df.iterrows():
|
||||
count += 1
|
||||
try:
|
||||
# 数据转换前的类型检查
|
||||
try:
|
||||
status = "0" if row["status"] == "正常" else "1"
|
||||
except ValueError:
|
||||
error_msgs.append(f"第{count}行: 状态必须是'正常'或'停用'")
|
||||
continue
|
||||
|
||||
# 构建用户数据
|
||||
data = {
|
||||
"name": str(row["name"]),
|
||||
"status": status,
|
||||
"description": str(row["description"]),
|
||||
}
|
||||
|
||||
# 处理用户导入
|
||||
exists_obj = await Demo01CRUD(auth).get(name=data["name"])
|
||||
if exists_obj:
|
||||
if update_support:
|
||||
await Demo01CRUD(auth).update(id=exists_obj.id, data=data)
|
||||
success_count += 1
|
||||
else:
|
||||
error_msgs.append(f"第{count}行: 对象 {data['name']} 已存在")
|
||||
else:
|
||||
await Demo01CRUD(auth).create(data=data)
|
||||
success_count += 1
|
||||
|
||||
except Exception as e:
|
||||
error_msgs.append(f"第{count}行: {e!s}")
|
||||
continue
|
||||
|
||||
# 返回详细的导入结果
|
||||
result = f"成功导入 {success_count} 条数据"
|
||||
if error_msgs:
|
||||
result += "\n错误信息:\n" + "\n".join(error_msgs)
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
log.error(f"批量导入用户失败: {e!s}")
|
||||
raise CustomException(msg=f"导入失败: {e!s}")
|
||||
|
||||
@classmethod
|
||||
async def import_template_download_service(cls) -> bytes:
|
||||
"""
|
||||
下载导入模板
|
||||
|
||||
返回:
|
||||
- bytes: Excel文件字节流
|
||||
"""
|
||||
header_list = ["名称", "状态", "描述"]
|
||||
selector_header_list = ["状态"]
|
||||
option_list = [{"状态": ["正常", "停用"]}]
|
||||
return ExcelUtil.get_excel_template(
|
||||
header_list=header_list,
|
||||
selector_header_list=selector_header_list,
|
||||
option_list=option_list,
|
||||
)
|
||||
Reference in New Issue
Block a user