mirror of
https://github.com/fastapiadmin/FastapiAdmin.git
synced 2026-09-20 20:39:55 +00:00
feat: 添加演示模块并优化日期选择器组件
refactor: 重构文件导入组件为通用组件 fix: 修复导出文件名统一问题 docs: 更新README添加二次开发教程 style: 统一系统管理页面的日期选择器实现 chore: 更新数据库迁移脚本和初始化数据 perf: 优化前端页面日期范围选择交互 test: 添加演示模块相关测试文件 build: 更新依赖项配置 ci: 调整CI/CD脚本配置
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
# -*- 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.base_params import PaginationQueryParams
|
||||
from app.core.dependencies import AuthPermission
|
||||
from app.core.router_class import OperationLogRoute
|
||||
from app.core.base_schema import BatchSetAvailable
|
||||
from app.core.logger import logger
|
||||
from app.common.request import PaginationService
|
||||
from app.utils.common_util import bytes2file_response
|
||||
from app.api.v1.schemas.system.auth_schema import AuthSchema
|
||||
from app.api.v1.params.demo.example_param import ExampleQueryParams
|
||||
from app.api.v1.services.demo.example_service import ExampleService
|
||||
from app.api.v1.schemas.demo.example_schema import (
|
||||
ExampleCreateSchema,
|
||||
ExampleUpdateSchema
|
||||
)
|
||||
|
||||
|
||||
router = APIRouter(route_class=OperationLogRoute)
|
||||
|
||||
@router.get("/detail/{id}", summary="获取示例详情", description="获取示例详情")
|
||||
async def get_obj_detail_controller(
|
||||
id: int = Path(..., description="示例ID"),
|
||||
auth: AuthSchema = Depends(AuthPermission(permissions=["demo:example:query"]))
|
||||
) -> JSONResponse:
|
||||
result_dict = await ExampleService.get_example_detail_service(id=id, auth=auth)
|
||||
logger.info(f"获取示例详情成功 {id}")
|
||||
return SuccessResponse(data=result_dict, msg="获取示例详情成功")
|
||||
|
||||
@router.get("/list", summary="查询示例列表", description="查询示例列表")
|
||||
async def get_obj_list_controller(
|
||||
page: PaginationQueryParams = Depends(),
|
||||
search: ExampleQueryParams = Depends(),
|
||||
auth: AuthSchema = Depends(AuthPermission(permissions=["demo:example:query"]))
|
||||
) -> JSONResponse:
|
||||
result_dict_list = await ExampleService.get_example_list_service(auth=auth, search=search, order_by=page.order_by)
|
||||
result_dict = await PaginationService.get_page_obj(data_list= result_dict_list, page_no= page.page_no, page_size = page.page_size)
|
||||
logger.info(f"查询示例列表成功")
|
||||
return SuccessResponse(data=result_dict, msg="查询公告列表成功")
|
||||
|
||||
@router.post("/create", summary="创建示例", description="创建示例")
|
||||
async def create_obj_controller(
|
||||
data: ExampleCreateSchema,
|
||||
auth: AuthSchema = Depends(AuthPermission(permissions=["demo:example:create"]))
|
||||
) -> JSONResponse:
|
||||
result_dict = await ExampleService.create_example_service(auth=auth, data=data)
|
||||
logger.info(f"创建示例成功: {result_dict}")
|
||||
return SuccessResponse(data=result_dict, msg="创建示例成功")
|
||||
|
||||
@router.put("/update", summary="修改示例", description="修改示例")
|
||||
async def update_obj_controller(
|
||||
data: ExampleUpdateSchema,
|
||||
auth: AuthSchema = Depends(AuthPermission(permissions=["demo:example:update"]))
|
||||
) -> JSONResponse:
|
||||
result_dict = await ExampleService.update_example_service(auth=auth, data=data)
|
||||
logger.info(f"修改示例成功: {result_dict}")
|
||||
return SuccessResponse(data=result_dict, msg="修改示例成功")
|
||||
|
||||
@router.delete("/delete", summary="删除示例", description="删除示例")
|
||||
async def delete_obj_controller(
|
||||
ids: list[int] = Body(..., description="ID列表"),
|
||||
auth: AuthSchema = Depends(AuthPermission(permissions=["demo:example:delete"]))
|
||||
) -> JSONResponse:
|
||||
await ExampleService.delete_example_service(auth=auth, ids=ids)
|
||||
logger.info(f"删除示例成功: {ids}")
|
||||
return SuccessResponse(msg="删除示例成功")
|
||||
|
||||
@router.patch("/available/setting", summary="批量修改示例状态", description="批量修改示例状态")
|
||||
async def batch_set_available_obj_controller(
|
||||
data: BatchSetAvailable,
|
||||
auth: AuthSchema = Depends(AuthPermission(permissions=["demo:example:patch"]))
|
||||
) -> JSONResponse:
|
||||
await ExampleService.set_example_available_service(auth=auth, data=data)
|
||||
logger.info(f"批量修改示例状态成功: {data.ids}")
|
||||
return SuccessResponse(msg="批量修改示例状态成功")
|
||||
|
||||
@router.post('/export', summary="导出示例", description="导出示例")
|
||||
async def export_obj_list_controller(
|
||||
search: ExampleQueryParams = Depends(),
|
||||
auth: AuthSchema = Depends(AuthPermission(permissions=["demo:example:export"]))
|
||||
) -> StreamingResponse:
|
||||
# 获取全量数据
|
||||
result_dict_list = await ExampleService.get_example_list_service(search=search, auth=auth)
|
||||
export_result = await ExampleService.batch_export_service(obj_list=result_dict_list)
|
||||
logger.info('导出示例成功')
|
||||
|
||||
return StreamResponse(
|
||||
data=bytes2file_response(export_result),
|
||||
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
headers = {
|
||||
'Content-Disposition': 'attachment; filename=example.xlsx'
|
||||
}
|
||||
)
|
||||
|
||||
@router.post('/import', summary="导入示例", description="导入示例")
|
||||
async def import_obj_list_controller(
|
||||
file: UploadFile,
|
||||
auth: AuthSchema = Depends(AuthPermission(permissions=["demo:example:import"]))
|
||||
) -> JSONResponse:
|
||||
batch_import_result = await ExampleService.batch_import_service(file=file, auth=auth, update_support=True)
|
||||
logger.info(f"导入示例成功: {batch_import_result}")
|
||||
return SuccessResponse(data=batch_import_result, msg="导入示例成功")
|
||||
|
||||
@router.post('/download/template', summary="获取示例导入模板", description="获取示例导入模板", dependencies=[Depends(AuthPermission(permissions=["demo:example:download"]))])
|
||||
async def export_obj_template_controller()-> StreamingResponse:
|
||||
example_import_template_result = await ExampleService.import_template_download_service()
|
||||
logger.info('获取示例导入模板成功')
|
||||
|
||||
return StreamResponse(
|
||||
data=bytes2file_response(example_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'
|
||||
}
|
||||
)
|
||||
@@ -83,7 +83,7 @@ async def export_obj_list_controller(
|
||||
data=bytes2file_response(export_result),
|
||||
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
headers = {
|
||||
'Content-Disposition': 'attachment; filename=data.xlsx'
|
||||
'Content-Disposition': 'attachment; filename=job.xlsx'
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -89,7 +89,7 @@ async def export_type_list_controller(
|
||||
data=bytes2file_response(export_result),
|
||||
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
headers = {
|
||||
'Content-Disposition': 'attachment; filename=data.xlsx'
|
||||
'Content-Disposition': 'attachment; filename=config.xlsx'
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -107,7 +107,7 @@ async def export_type_list_controller(
|
||||
data=bytes2file_response(export_result),
|
||||
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
headers = {
|
||||
'Content-Disposition': 'attachment; filename=data.xlsx'
|
||||
'Content-Disposition': 'attachment; filename=dict_type.xlsx'
|
||||
}
|
||||
)
|
||||
|
||||
@@ -185,7 +185,7 @@ async def export_data_list_controller(
|
||||
data=bytes2file_response(export_result),
|
||||
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
headers = {
|
||||
'Content-Disposition': 'attachment; filename=data.xlsx'
|
||||
'Content-Disposition': 'attachment; filename=dice_data.xlsx'
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@ async def export_obj_list_controller(
|
||||
data=bytes2file_response(export_result),
|
||||
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
headers = {
|
||||
'Content-Disposition': 'attachment; filename=data.xlsx'
|
||||
'Content-Disposition': 'attachment; filename=notice.xlsx'
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -66,6 +66,6 @@ async def export_obj_list_controller(
|
||||
data=bytes2file_response(operation_log_export_result),
|
||||
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
headers = {
|
||||
'Content-Disposition': 'attachment; filename=data.xlsx'
|
||||
'Content-Disposition': 'attachment; filename=log.xlsx'
|
||||
}
|
||||
)
|
||||
|
||||
@@ -99,6 +99,6 @@ async def export_obj_list_controller(
|
||||
data=bytes2file_response(position_export_result),
|
||||
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
headers = {
|
||||
'Content-Disposition': 'attachment; filename=data.xlsx'
|
||||
'Content-Disposition': 'attachment; filename=position.xlsx'
|
||||
}
|
||||
)
|
||||
|
||||
@@ -110,6 +110,6 @@ async def export_obj_list_controller(
|
||||
data=bytes2file_response(role_export_result),
|
||||
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
headers = {
|
||||
'Content-Disposition': 'attachment; filename=data.xlsx'
|
||||
'Content-Disposition': 'attachment; filename=role.xlsx'
|
||||
}
|
||||
)
|
||||
|
||||
@@ -190,7 +190,7 @@ async def export_obj_list_controller(
|
||||
data=bytes2file_response(user_export_result),
|
||||
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
headers = {
|
||||
'Content-Disposition': 'attachment; filename=data.xlsx'
|
||||
'Content-Disposition': 'attachment; filename=user.xlsx'
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Dict, List, Optional, Sequence
|
||||
|
||||
from app.core.base_crud import CRUDBase
|
||||
from app.api.v1.models.demo.example_model import ExampleModel
|
||||
from app.api.v1.schemas.demo.example_schema import ExampleCreateSchema, ExampleUpdateSchema
|
||||
from app.api.v1.schemas.system.auth_schema import AuthSchema
|
||||
|
||||
|
||||
class ExampleCRUD(CRUDBase[ExampleModel, ExampleCreateSchema, ExampleUpdateSchema]):
|
||||
"""示例数据层"""
|
||||
|
||||
def __init__(self, auth: AuthSchema) -> None:
|
||||
"""初始化CRUD"""
|
||||
self.auth = auth
|
||||
super().__init__(model=ExampleModel, auth=auth)
|
||||
|
||||
async def get_by_id_crud(self, id: int) -> Optional[ExampleModel]:
|
||||
"""详情"""
|
||||
return await self.get(id=id)
|
||||
|
||||
async def get_list_crud(self, search: Dict = None, order_by: List[Dict[str, str]] = None) -> Sequence[ExampleModel]:
|
||||
"""列表查询"""
|
||||
return await self.list(search=search, order_by=order_by)
|
||||
|
||||
async def create_crud(self, data: ExampleCreateSchema) -> Optional[ExampleModel]:
|
||||
"""创建"""
|
||||
return await self.create(data=data)
|
||||
|
||||
async def update_crud(self, id: int, data: ExampleUpdateSchema) -> Optional[ExampleModel]:
|
||||
"""更新"""
|
||||
return await self.update(id=id, data=data)
|
||||
|
||||
async def delete_crud(self, ids: List[int]) -> None:
|
||||
"""删除"""
|
||||
return await self.delete(ids=ids)
|
||||
|
||||
async def set_available_crud(self, ids: List[int], status: bool) -> None:
|
||||
"""批量设置可用状态"""
|
||||
return await self.set(ids=ids, status=status)
|
||||
@@ -9,10 +9,10 @@ from app.api.v1.schemas.system.auth_schema import AuthSchema
|
||||
|
||||
|
||||
class NoticeCRUD(CRUDBase[NoticeModel, NoticeCreateSchema, NoticeUpdateSchema]):
|
||||
"""操作日志数据层"""
|
||||
"""公告数据层"""
|
||||
|
||||
def __init__(self, auth: AuthSchema) -> None:
|
||||
"""初始化操作日志CRUD"""
|
||||
"""初始化CRUD"""
|
||||
self.auth = auth
|
||||
super().__init__(model=NoticeModel, auth=auth)
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from datetime import datetime
|
||||
from sqlalchemy import Boolean, Column, DateTime, Float, ForeignKey, Integer, String, Text
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from app.core.base_model import ModelBase
|
||||
|
||||
|
||||
class ExampleModel(ModelBase):
|
||||
"""
|
||||
示例表
|
||||
"""
|
||||
|
||||
__tablename__ = 'demo_example'
|
||||
__table_args__ = ({'comment': '示例表'})
|
||||
|
||||
id=Column(Integer, primary_key=True, autoincrement=True, comment='ID')
|
||||
name=Column(String(64), nullable=True, default='', comment='名称')
|
||||
description=Column(Text, nullable=True, comment='描述')
|
||||
status = Column(Boolean, default=False, nullable=True, comment='任务状态:正常,停止')
|
||||
|
||||
# 审计字段
|
||||
description = Column(Text, nullable=True, comment="备注说明")
|
||||
created_at = Column(DateTime, nullable=True, default=datetime.now, comment='创建时间')
|
||||
updated_at = Column(DateTime, nullable=True, default=datetime.now, onupdate=datetime.now, comment='更新时间')
|
||||
creator_id = Column(
|
||||
Integer,
|
||||
ForeignKey("system_users.id", ondelete="SET NULL", onupdate="CASCADE"),
|
||||
nullable=True,
|
||||
index=True,
|
||||
comment="创建人ID"
|
||||
)
|
||||
creator = relationship(
|
||||
"UserModel",
|
||||
foreign_keys=creator_id,
|
||||
lazy="joined",
|
||||
post_update=True,
|
||||
uselist=False
|
||||
)
|
||||
|
||||
@@ -12,7 +12,7 @@ class JobModel(ModelBase):
|
||||
定时任务调度表
|
||||
"""
|
||||
|
||||
__tablename__ = 'system_job'
|
||||
__tablename__ = 'monitor_job'
|
||||
__table_args__ = ({'comment': '定时任务调度表'})
|
||||
|
||||
id=Column(Integer, primary_key=True, autoincrement=True, comment='任务ID')
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import Query
|
||||
|
||||
from app.core.validator import DateTimeStr
|
||||
|
||||
class ExampleQueryParams:
|
||||
"""示例查询参数"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: Optional[str] = Query(None, description="名称"),
|
||||
status: Optional[bool] = Query(None, description="是否启用"),
|
||||
creator: Optional[int] = Query(None, description="创建人"),
|
||||
start_time: Optional[DateTimeStr] = Query(None, description="开始时间", example="2023-01-01 00:00:00"),
|
||||
end_time: Optional[DateTimeStr] = Query(None, description="结束时间", example="2023-12-31 23:59:59"),
|
||||
) -> None:
|
||||
super().__init__()
|
||||
|
||||
# 模糊查询字段
|
||||
self.name = ("like", name)
|
||||
|
||||
# 精确查询字段
|
||||
self.creator_id = creator
|
||||
self.status = status
|
||||
|
||||
# 时间范围查询
|
||||
if start_time and end_time:
|
||||
start_datetime = datetime.strptime(str(start_time), '%Y-%m-%d %H:%M:%S')
|
||||
end_datetime = datetime.strptime(str(end_time), '%Y-%m-%d %H:%M:%S')
|
||||
self.created_at = ("between", (start_datetime, end_datetime))
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.core.base_schema import BaseSchema
|
||||
|
||||
|
||||
class ExampleCreateSchema(BaseModel):
|
||||
"""新增模型"""
|
||||
name: str = Field(..., max_length=50, description='名称')
|
||||
status: bool = Field(True, description="是否启用(True:启用 False:禁用)")
|
||||
description: Optional[str] = Field(None, max_length=255, description="描述")
|
||||
|
||||
|
||||
class ExampleUpdateSchema(ExampleCreateSchema):
|
||||
"""更新模型"""
|
||||
id: int = Field(..., gt=0, description="示例ID")
|
||||
|
||||
|
||||
class ExampleOutSchema(ExampleCreateSchema, BaseSchema):
|
||||
"""响应模型"""
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
@@ -0,0 +1,192 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import io
|
||||
from typing import Any, List, Dict
|
||||
from fastapi import UploadFile
|
||||
import pandas as pd
|
||||
|
||||
from app.api.v1.schemas.system.auth_schema import AuthSchema
|
||||
from app.api.v1.schemas.demo.example_schema import ExampleCreateSchema, ExampleUpdateSchema, ExampleOutSchema
|
||||
from app.core.base_schema import BatchSetAvailable
|
||||
from app.api.v1.params.demo.example_param import ExampleQueryParams
|
||||
from app.api.v1.cruds.demo.example_crud import ExampleCRUD
|
||||
from app.core.exceptions import CustomException
|
||||
from app.utils.excel_util import ExcelUtil
|
||||
from app.core.logger import logger
|
||||
|
||||
|
||||
class ExampleService:
|
||||
"""
|
||||
示例管理模块服务层
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
async def get_example_detail_service(cls, auth: AuthSchema, id: int) -> Dict:
|
||||
"""详情"""
|
||||
obj = await ExampleCRUD(auth).get_by_id_crud(id=id)
|
||||
return ExampleOutSchema.model_validate(obj).model_dump()
|
||||
|
||||
@classmethod
|
||||
async def get_example_list_service(cls, auth: AuthSchema, search: ExampleQueryParams = None, order_by: List[Dict[str, str]] = None) -> List[Dict]:
|
||||
"""列表查询"""
|
||||
if order_by:
|
||||
order_by = eval(order_by)
|
||||
obj_list = await ExampleCRUD(auth).get_list_crud(search=search.__dict__, order_by=order_by)
|
||||
return [ExampleOutSchema.model_validate(obj).model_dump() for obj in obj_list]
|
||||
|
||||
@classmethod
|
||||
async def create_example_service(cls, auth: AuthSchema, data: ExampleCreateSchema) -> Dict:
|
||||
"""创建"""
|
||||
obj = await ExampleCRUD(auth).get(name=data.name)
|
||||
if obj:
|
||||
raise CustomException(msg='创建失败,名称已存在')
|
||||
obj = await ExampleCRUD(auth).create_crud(data=data)
|
||||
return ExampleOutSchema.model_validate(obj).model_dump()
|
||||
|
||||
@classmethod
|
||||
async def update_example_service(cls, auth: AuthSchema, data: ExampleUpdateSchema) -> Dict:
|
||||
"""更新"""
|
||||
obj = await ExampleCRUD(auth).get_by_id_crud(id=data.id)
|
||||
if not obj:
|
||||
raise CustomException(msg='更新失败,该数据不存在')
|
||||
exist_obj = await ExampleCRUD(auth).get(name=data.name)
|
||||
if exist_obj and exist_obj.id != data.id:
|
||||
raise CustomException(msg='更新失败,名称重复')
|
||||
obj = await ExampleCRUD(auth).update_crud(id=data.id, data=data)
|
||||
return ExampleOutSchema.model_validate(obj).model_dump()
|
||||
|
||||
@classmethod
|
||||
async def delete_example_service(cls, auth: AuthSchema, ids: list[int]) -> None:
|
||||
"""删除"""
|
||||
if len(ids) < 1:
|
||||
raise CustomException(msg='删除失败,删除对象不能为空')
|
||||
for id in ids:
|
||||
obj = await ExampleCRUD(auth).get_by_id_crud(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg='删除失败,该数据不存在')
|
||||
await ExampleCRUD(auth).delete_crud(ids=ids)
|
||||
|
||||
@classmethod
|
||||
async def set_example_available_service(cls, auth: AuthSchema, data: BatchSetAvailable) -> None:
|
||||
"""批量设置状态"""
|
||||
await ExampleCRUD(auth).set_available_crud(ids=data.ids, status=data.status)
|
||||
|
||||
@classmethod
|
||||
async def batch_export_service(cls, obj_list: List[Dict[str, Any]]) -> bytes:
|
||||
"""批量导出"""
|
||||
mapping_dict = {
|
||||
'id': '编号',
|
||||
'name': '名称',
|
||||
'status': '状态',
|
||||
'description': '备注',
|
||||
'created_at': '创建时间',
|
||||
'updated_at': '更新时间',
|
||||
'creator': '创建者',
|
||||
}
|
||||
|
||||
# 复制数据并转换状态
|
||||
data = obj_list.copy()
|
||||
for item in data:
|
||||
# 处理状态
|
||||
item['status'] = '正常' if item.get('status') else '停用'
|
||||
# 处理公告类型
|
||||
item['creator'] = item.get('creator', {}).get('name', '未知') if isinstance(item.get('creator'), dict) else '未知'
|
||||
|
||||
return ExcelUtil.export_list2excel(list_data=obj_list, mapping_dict=mapping_dict)
|
||||
|
||||
@classmethod
|
||||
async def batch_import_service(cls, auth: AuthSchema, file: UploadFile, update_support: bool = False) -> 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']
|
||||
for field in required_fields:
|
||||
if df[field].isnull().any():
|
||||
missing_rows = df[df[field].isnull()].index.tolist()
|
||||
raise CustomException(msg=f"{[k for k,v in header_dict.items() if v == field][0]}不能为空,第{[i+1 for i in missing_rows]}行")
|
||||
|
||||
error_msgs = []
|
||||
success_count = 0
|
||||
|
||||
# 处理每一行数据
|
||||
for index, row in df.iterrows():
|
||||
try:
|
||||
# 数据转换前的类型检查
|
||||
try:
|
||||
name = str(row['name'])
|
||||
except ValueError:
|
||||
error_msgs.append(f"第{index+1}行: 名称必须是字符串")
|
||||
continue
|
||||
try:
|
||||
status = True if row['status'] == '正常' else False
|
||||
except ValueError:
|
||||
error_msgs.append(f"第{index+1}行: 状态必须是'正常'或'停用'")
|
||||
continue
|
||||
|
||||
# 构建用户数据
|
||||
data = {
|
||||
"name": name,
|
||||
"status": status,
|
||||
"description": str(row['description']).strip() if not pd.isna(row['description']) else None,
|
||||
}
|
||||
|
||||
# 处理用户导入
|
||||
exists_user = await ExampleCRUD(auth).get(name=data["name"])
|
||||
if exists_user:
|
||||
if update_support:
|
||||
await ExampleCRUD(auth).update(id=exists_user.id, data=data)
|
||||
success_count += 1
|
||||
else:
|
||||
error_msgs.append(f"第{index+1}行: 用户 {data['username']} 已存在")
|
||||
else:
|
||||
await ExampleCRUD(auth).create(data=data)
|
||||
success_count += 1
|
||||
|
||||
except Exception as e:
|
||||
error_msgs.append(f"第{index+1}行: {str(e)}")
|
||||
continue
|
||||
|
||||
# 返回详细的导入结果
|
||||
result = f"成功导入 {success_count} 条数据"
|
||||
if error_msgs:
|
||||
result += "\n错误信息:\n" + "\n".join(error_msgs)
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"批量导入用户失败: {str(e)}")
|
||||
raise CustomException(msg=f"导入失败: {str(e)}")
|
||||
|
||||
@classmethod
|
||||
async def import_template_download_service(cls) -> bytes:
|
||||
"""下载导入模板"""
|
||||
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
|
||||
)
|
||||
@@ -0,0 +1,11 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.v1.controllers.demo.example_controller import router as ExampleRouter
|
||||
|
||||
|
||||
DemoApiRouter = APIRouter(prefix="/demo")
|
||||
|
||||
|
||||
DemoApiRouter.include_router(router=ExampleRouter, prefix="/example", tags=["示例模块"])
|
||||
Reference in New Issue
Block a user