upload project source code
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Path, UploadFile
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
import urllib.parse
|
||||
|
||||
from app.common.response import StreamResponse, SuccessResponse
|
||||
from app.core.router_class import OperationLogRoute
|
||||
from app.utils.common_util import bytes2file_response
|
||||
from app.core.base_params import PaginationQueryParam
|
||||
from app.core.dependencies import AuthPermission
|
||||
from app.core.base_schema import BatchSetAvailable
|
||||
from app.core.logger import log
|
||||
from app.api.v1.module_system.auth.schema import AuthSchema
|
||||
from .service import DemoService
|
||||
from .schema import (
|
||||
DemoCreateSchema,
|
||||
DemoUpdateSchema,
|
||||
DemoQueryParam
|
||||
)
|
||||
|
||||
|
||||
DemoRouter = APIRouter(route_class=OperationLogRoute, prefix="/demo", tags=["示例模块"])
|
||||
|
||||
@DemoRouter.get("/detail/{id}", summary="获取示例详情", description="获取示例详情")
|
||||
async def get_obj_detail_controller(
|
||||
id: int = Path(..., description="示例ID"),
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_gencode:demo:query"]))
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
获取示例详情
|
||||
|
||||
参数:
|
||||
- id (int): 示例ID
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
返回:
|
||||
- JSONResponse: 包含示例详情的JSON响应
|
||||
"""
|
||||
result_dict = await DemoService.detail_service(id=id, auth=auth)
|
||||
log.info(f"获取示例详情成功 {id}")
|
||||
return SuccessResponse(data=result_dict, msg="获取示例详情成功")
|
||||
|
||||
@DemoRouter.get("/list", summary="查询示例列表", description="查询示例列表")
|
||||
async def get_obj_list_controller(
|
||||
page: PaginationQueryParam = Depends(),
|
||||
search: DemoQueryParam = Depends(),
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_gencode:demo:query"]))
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
查询示例列表
|
||||
|
||||
参数:
|
||||
- page (PaginationQueryParam): 分页查询参数
|
||||
- search (DemoQueryParam): 查询参数
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
返回:
|
||||
- JSONResponse: 包含示例列表分页信息的JSON响应
|
||||
"""
|
||||
# 使用数据库分页而不是应用层分页
|
||||
result_dict = await DemoService.page_service(
|
||||
auth=auth,
|
||||
page_no=page.page_no,
|
||||
page_size=page.page_size,
|
||||
search=search,
|
||||
order_by=page.order_by
|
||||
)
|
||||
log.info("查询示例列表成功")
|
||||
return SuccessResponse(data=result_dict, msg="查询示例列表成功")
|
||||
|
||||
@DemoRouter.post("/create", summary="创建示例", description="创建示例")
|
||||
async def create_obj_controller(
|
||||
data: DemoCreateSchema,
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_gencode:demo:create"]))
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
创建示例
|
||||
|
||||
参数:
|
||||
- data (DemoCreateSchema): 示例创建模型
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
返回:
|
||||
- JSONResponse: 包含创建示例详情的JSON响应
|
||||
"""
|
||||
result_dict = await DemoService.create_service(auth=auth, data=data)
|
||||
log.info(f"创建示例成功: {result_dict.get('name')}")
|
||||
return SuccessResponse(data=result_dict, msg="创建示例成功")
|
||||
|
||||
@DemoRouter.put("/update/{id}", summary="修改示例", description="修改示例")
|
||||
async def update_obj_controller(
|
||||
data: DemoUpdateSchema,
|
||||
id: int = Path(..., description="示例ID"),
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_gencode:demo:update"]))
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
修改示例
|
||||
|
||||
参数:
|
||||
- data (DemoUpdateSchema): 示例更新模型
|
||||
- id (int): 示例ID
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
返回:
|
||||
- JSONResponse: 包含修改示例详情的JSON响应
|
||||
"""
|
||||
result_dict = await DemoService.update_service(auth=auth, id=id, data=data)
|
||||
log.info(f"修改示例成功: {result_dict.get('name')}")
|
||||
return SuccessResponse(data=result_dict, msg="修改示例成功")
|
||||
|
||||
@DemoRouter.delete("/delete", summary="删除示例", description="删除示例")
|
||||
async def delete_obj_controller(
|
||||
ids: list[int] = Body(..., description="ID列表"),
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_gencode:demo:delete"]))
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
删除示例
|
||||
|
||||
参数:
|
||||
- ids (list[int]): 示例ID列表
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
返回:
|
||||
- JSONResponse: 包含删除示例详情的JSON响应
|
||||
"""
|
||||
await DemoService.delete_service(auth=auth, ids=ids)
|
||||
log.info(f"删除示例成功: {ids}")
|
||||
return SuccessResponse(msg="删除示例成功")
|
||||
|
||||
@DemoRouter.patch("/available/setting", summary="批量修改示例状态", description="批量修改示例状态")
|
||||
async def batch_set_available_obj_controller(
|
||||
data: BatchSetAvailable,
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_gencode:demo:patch"]))
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
批量修改示例状态
|
||||
|
||||
参数:
|
||||
- data (BatchSetAvailable): 批量修改示例状态模型
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
返回:
|
||||
- JSONResponse: 包含批量修改示例状态详情的JSON响应
|
||||
"""
|
||||
await DemoService.set_available_service(auth=auth, data=data)
|
||||
log.info(f"批量修改示例状态成功: {data.ids}")
|
||||
return SuccessResponse(msg="批量修改示例状态成功")
|
||||
|
||||
@DemoRouter.post('/export', summary="导出示例", description="导出示例")
|
||||
async def export_obj_list_controller(
|
||||
search: DemoQueryParam = Depends(),
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_gencode:demo:export"]))
|
||||
) -> StreamingResponse:
|
||||
"""
|
||||
导出示例
|
||||
|
||||
参数:
|
||||
- search (DemoQueryParam): 查询参数
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
返回:
|
||||
- StreamingResponse: 包含示例列表的Excel文件流响应
|
||||
"""
|
||||
result_dict_list = await DemoService.list_service(search=search, auth=auth)
|
||||
export_result = await DemoService.batch_export_service(obj_list=result_dict_list)
|
||||
log.info('导出示例成功')
|
||||
|
||||
return StreamResponse(
|
||||
data=bytes2file_response(export_result),
|
||||
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
headers={
|
||||
'Content-Disposition': 'attachment; filename=demo.xlsx'
|
||||
}
|
||||
)
|
||||
|
||||
@DemoRouter.post('/import', summary="导入示例", description="导入示例")
|
||||
async def import_obj_list_controller(
|
||||
file: UploadFile,
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_gencode:demo:import"]))
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
导入示例
|
||||
|
||||
参数:
|
||||
- file (UploadFile): 导入的Excel文件
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
返回:
|
||||
- JSONResponse: 包含导入示例详情的JSON响应
|
||||
"""
|
||||
batch_import_result = await DemoService.batch_import_service(file=file, auth=auth, update_support=True)
|
||||
log.info(f"导入示例成功: {batch_import_result}")
|
||||
return SuccessResponse(data=batch_import_result, msg="导入示例成功")
|
||||
|
||||
@DemoRouter.post('/download/template', summary="获取示例导入模板", description="获取示例导入模板", dependencies=[Depends(AuthPermission(["module_gencode:demo:download"]))])
|
||||
async def export_obj_template_controller() -> StreamingResponse:
|
||||
"""
|
||||
获取示例导入模板
|
||||
|
||||
返回:
|
||||
- StreamingResponse: 包含示例导入模板的Excel文件流响应
|
||||
"""
|
||||
import_template_result = await DemoService.import_template_download_service()
|
||||
log.info('获取示例导入模板成功')
|
||||
|
||||
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("示例导入模板.xlsx")}',
|
||||
'Access-Control-Expose-Headers': 'Content-Disposition'
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,124 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from collections.abc import Sequence
|
||||
from app.core.base_crud import CRUDBase
|
||||
|
||||
from app.api.v1.module_system.auth.schema import AuthSchema
|
||||
from .model import DemoModel
|
||||
from .schema import DemoCreateSchema, DemoUpdateSchema, DemoOutSchema
|
||||
|
||||
|
||||
class DemoCRUD(CRUDBase[DemoModel, DemoCreateSchema, DemoUpdateSchema]):
|
||||
"""示例数据层"""
|
||||
|
||||
def __init__(self, auth: AuthSchema) -> None:
|
||||
"""
|
||||
初始化CRUD数据层
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
"""
|
||||
super().__init__(model=DemoModel, auth=auth)
|
||||
|
||||
async def get_by_id_crud(self, id: int, preload: list[str] | None = None) -> DemoModel | None:
|
||||
"""
|
||||
详情
|
||||
|
||||
参数:
|
||||
- id (int): 示例ID
|
||||
- preload (list[str] | None): 预加载关系,未提供时使用模型默认项
|
||||
|
||||
返回:
|
||||
- DemoModel | 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[DemoModel]:
|
||||
"""
|
||||
列表查询
|
||||
|
||||
参数:
|
||||
- search (dict | None): 查询参数
|
||||
- order_by (list[dict] | None): 排序参数
|
||||
- preload (list[str] | None): 预加载关系,未提供时使用模型默认项
|
||||
|
||||
返回:
|
||||
- Sequence[DemoModel]: 示例模型实例序列
|
||||
"""
|
||||
return await self.list(search=search, order_by=order_by, preload=preload)
|
||||
|
||||
async def create_crud(self, data: DemoCreateSchema) -> DemoModel | None:
|
||||
"""
|
||||
创建
|
||||
|
||||
参数:
|
||||
- data (DemoCreateSchema): 示例创建模型
|
||||
|
||||
返回:
|
||||
- DemoModel | None: 示例模型实例或None
|
||||
"""
|
||||
return await self.create(data=data)
|
||||
|
||||
async def update_crud(self, id: int, data: DemoUpdateSchema) -> DemoModel | None:
|
||||
"""
|
||||
更新
|
||||
|
||||
参数:
|
||||
- id (int): 示例ID
|
||||
- data (DemoUpdateSchema): 示例更新模型
|
||||
|
||||
返回:
|
||||
- DemoModel | 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=DemoOutSchema,
|
||||
preload=preload
|
||||
)
|
||||
@@ -0,0 +1,25 @@
|
||||
'''
|
||||
Author: caoziyuan ziyuan.cao@zhuying.com
|
||||
Date: 2025-12-15 17:37:50
|
||||
LastEditors: caoziyuan ziyuan.cao@zhuying.com
|
||||
LastEditTime: 2025-12-22 17:25:22
|
||||
FilePath: \backend\app\api\v1\module_gencode\demo\model.py
|
||||
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
|
||||
'''
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from sqlalchemy import String
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.core.base_model import ModelMixin, UserMixin
|
||||
|
||||
|
||||
class DemoModel(ModelMixin, UserMixin):
|
||||
"""
|
||||
示例表
|
||||
"""
|
||||
__tablename__: str = 'gen_demo'
|
||||
__table_args__: dict[str, str] = ({'comment': '示例表'})
|
||||
__loader_options__: list[str] = ["created_by", "updated_by"]
|
||||
|
||||
name: Mapped[str | None] = mapped_column(String(64), nullable=True, default='', comment='名称')
|
||||
@@ -0,0 +1,76 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
from fastapi import Query
|
||||
|
||||
from app.core.validator import DateTimeStr
|
||||
from app.core.base_schema import BaseSchema, UserBySchema
|
||||
|
||||
|
||||
class DemoCreateSchema(BaseModel):
|
||||
"""新增模型"""
|
||||
name: str = Field(..., min_length=2, max_length=50, description='名称')
|
||||
status: str = Field(default="0", description="是否启用(0:启用 1:禁用)")
|
||||
description: str | None = Field(default=None, max_length=255, 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 self.name.isalnum() and not all(c in '-_' for c in self.name):
|
||||
raise ValueError('名称只能包含字母、数字、下划线和中划线')
|
||||
|
||||
return self
|
||||
|
||||
|
||||
class DemoUpdateSchema(DemoCreateSchema):
|
||||
"""更新模型"""
|
||||
...
|
||||
|
||||
|
||||
class DemoOutSchema(DemoCreateSchema, BaseSchema, UserBySchema):
|
||||
"""响应模型"""
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class DemoQueryParam:
|
||||
"""示例查询参数"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: 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 = ("like", name)
|
||||
|
||||
# 精确查询字段
|
||||
self.created_id = created_id
|
||||
self.updated_id = updated_id
|
||||
self.status = status
|
||||
|
||||
# 时间范围查询
|
||||
if created_time and len(created_time) == 2:
|
||||
self.created_time = ("between", (created_time[0], created_time[1]))
|
||||
if updated_time and len(updated_time) == 2:
|
||||
self.updated_time = ("between", (updated_time[0], updated_time[1]))
|
||||
@@ -0,0 +1,312 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import io
|
||||
from typing import Any
|
||||
from fastapi import UploadFile
|
||||
import pandas as pd
|
||||
|
||||
from app.core.base_schema import BatchSetAvailable
|
||||
from app.core.exceptions import CustomException
|
||||
from app.utils.excel_util import ExcelUtil
|
||||
from app.core.logger import log
|
||||
|
||||
from app.api.v1.module_system.auth.schema import AuthSchema
|
||||
from .schema import DemoCreateSchema, DemoUpdateSchema, DemoOutSchema, DemoQueryParam
|
||||
from .crud import DemoCRUD
|
||||
|
||||
|
||||
class DemoService:
|
||||
"""
|
||||
示例管理模块服务层
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
async def detail_service(cls, auth: AuthSchema, id: int) -> dict:
|
||||
"""
|
||||
详情
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- id (int): 示例ID
|
||||
|
||||
返回:
|
||||
- dict: 示例模型实例字典
|
||||
"""
|
||||
obj = await DemoCRUD(auth).get_by_id_crud(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg="该数据不存在")
|
||||
return DemoOutSchema.model_validate(obj).model_dump()
|
||||
|
||||
@classmethod
|
||||
async def list_service(cls, auth: AuthSchema, search: DemoQueryParam | None = None, order_by: list[dict[str, str]] | None = None) -> list[dict]:
|
||||
"""
|
||||
列表查询
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- search (DemoQueryParam | None): 查询参数
|
||||
- order_by (list[dict[str, str]] | None): 排序参数
|
||||
|
||||
返回:
|
||||
- list[dict]: 示例模型实例字典列表
|
||||
"""
|
||||
search_dict = search.__dict__ if search else None
|
||||
obj_list = await DemoCRUD(auth).list_crud(search=search_dict, order_by=order_by)
|
||||
return [DemoOutSchema.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: DemoQueryParam | None = None, order_by: list[dict[str, str]] | None = None) -> dict:
|
||||
"""
|
||||
分页查询
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- page_no (int): 页码
|
||||
- page_size (int): 每页数量
|
||||
- search (DemoQueryParam | 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 DemoCRUD(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: DemoCreateSchema) -> dict:
|
||||
"""
|
||||
创建
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- data (DemoCreateSchema): 示例创建模型
|
||||
|
||||
返回:
|
||||
- dict: 示例模型实例字典
|
||||
"""
|
||||
obj = await DemoCRUD(auth).get(name=data.name)
|
||||
if obj:
|
||||
raise CustomException(msg='创建失败,名称已存在')
|
||||
obj = await DemoCRUD(auth).create_crud(data=data)
|
||||
return DemoOutSchema.model_validate(obj).model_dump()
|
||||
|
||||
@classmethod
|
||||
async def update_service(cls, auth: AuthSchema, id: int, data: DemoUpdateSchema) -> dict:
|
||||
"""
|
||||
更新
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- id (int): 示例ID
|
||||
- data (DemoUpdateSchema): 示例更新模型
|
||||
|
||||
返回:
|
||||
- dict: 示例模型实例字典
|
||||
"""
|
||||
# 检查数据是否存在
|
||||
obj = await DemoCRUD(auth).get_by_id_crud(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg='更新失败,该数据不存在')
|
||||
|
||||
# 检查名称是否重复
|
||||
exist_obj = await DemoCRUD(auth).get(name=data.name)
|
||||
if exist_obj and exist_obj.id != id:
|
||||
raise CustomException(msg='更新失败,名称重复')
|
||||
|
||||
obj = await DemoCRUD(auth).update_crud(id=id, data=data)
|
||||
return DemoOutSchema.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 DemoCRUD(auth).get_by_id_crud(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg=f'删除失败,ID为{id}的数据不存在')
|
||||
|
||||
await DemoCRUD(auth).delete_crud(ids=ids)
|
||||
|
||||
@classmethod
|
||||
async def set_available_service(cls, auth: AuthSchema, data: BatchSetAvailable) -> None:
|
||||
"""
|
||||
批量设置状态
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- data (BatchSetAvailable): 批量设置状态模型
|
||||
|
||||
返回:
|
||||
- None
|
||||
"""
|
||||
await DemoCRUD(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 = [k for k,v in header_dict.items() if v == field][0]
|
||||
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 = True if row['status'] == '正常' else False
|
||||
except ValueError:
|
||||
error_msgs.append(f"第{count}行: 状态必须是'正常'或'停用'")
|
||||
continue
|
||||
|
||||
# 构建用户数据
|
||||
data = {
|
||||
"name": str(row['name']),
|
||||
"status": status,
|
||||
"description": str(row['description']),
|
||||
}
|
||||
|
||||
# 处理用户导入
|
||||
exists_obj = await DemoCRUD(auth).get(name=data["name"])
|
||||
if exists_obj:
|
||||
if update_support:
|
||||
await DemoCRUD(auth).update(id=exists_obj.id, data=data)
|
||||
success_count += 1
|
||||
else:
|
||||
error_msgs.append(f"第{count}行: 对象 {data['name']} 已存在")
|
||||
else:
|
||||
await DemoCRUD(auth).create(data=data)
|
||||
success_count += 1
|
||||
|
||||
except Exception as e:
|
||||
error_msgs.append(f"第{count}行: {str(e)}")
|
||||
continue
|
||||
|
||||
# 返回详细的导入结果
|
||||
result = f"成功导入 {success_count} 条数据"
|
||||
if error_msgs:
|
||||
result += "\n错误信息:\n" + "\n".join(error_msgs)
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
log.error(f"批量导入用户失败: {str(e)}")
|
||||
raise CustomException(msg=f"导入失败: {str(e)}")
|
||||
|
||||
@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