mirror of
https://github.com/fastapiadmin/FastapiAdmin.git
synced 2026-09-22 13:05:18 +00:00
style: 统一代码风格和格式 docs: 完善函数和方法的文档字符串 refactor(base_model): 移除冗余的表名和表参数生成方法 refactor(constant): 更新返回码注释格式 refactor(router_class): 添加路由处理器的详细文档 refactor(database): 完善数据库连接函数的文档 refactor(security): 添加认证类和方法的详细文档 refactor(validator): 更新验证器函数的文档格式 refactor(serialize): 优化序列化工具类的文档 refactor(response): 完善响应类的文档字符串 refactor(dependencies): 添加依赖函数的详细文档 refactor(initialize): 完善初始化脚本的文档 refactor(plugin): 添加生命周期和中间件注册的文档 refactor(service): 完善服务层方法的文档 refactor(controller): 添加控制器方法的详细文档 refactor(crud): 完善CRUD操作的文档字符串 refactor(schema): 简化模型类并移除冗余字段 refactor(param): 更新查询参数类的注释格式 refactor(template): 优化代码生成模板的格式 refactor(console): 添加控制台输出功能的实现 refactor(util): 完善工具函数的文档字符串
147 lines
6.1 KiB
Django/Jinja
147 lines
6.1 KiB
Django/Jinja
# -*- coding:utf-8 -*-
|
|
|
|
import io
|
|
from typing import Any, List, Dict, Optional
|
|
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 logger
|
|
from app.api.v1.module_system.auth.schema import AuthSchema
|
|
from .schema import {{ table_name|snake_to_pascal_case }}CreateSchema, {{ table_name|snake_to_pascal_case }}UpdateSchema, {{ table_name|snake_to_pascal_case }}OutSchema
|
|
from .param import {{ table_name|snake_to_pascal_case }}QueryParam
|
|
from .crud import {{ table_name|snake_to_pascal_case }}CRUD
|
|
|
|
|
|
class {{ table_name|snake_to_pascal_case }}Service:
|
|
"""
|
|
{{ function_name }}服务层
|
|
"""
|
|
|
|
@classmethod
|
|
async def detail_service(cls, auth: AuthSchema, id: int) -> Dict:
|
|
"""详情"""
|
|
obj = await {{ table_name|snake_to_pascal_case }}CRUD(auth).get_by_id_crud(id=id)
|
|
if not obj:
|
|
raise CustomException(msg="该数据不存在")
|
|
return {{ table_name|snake_to_pascal_case }}OutSchema.model_validate(obj).model_dump()
|
|
|
|
@classmethod
|
|
async def list_service(cls, auth: AuthSchema, search: Optional[{{ table_name|snake_to_pascal_case }}QueryParam] = None, order_by: Optional[List[Dict[str, str]]] = None) -> List[Dict]:
|
|
"""列表查询"""
|
|
search_dict = search.__dict__ if search else None
|
|
obj_list = await {{ table_name|snake_to_pascal_case }}CRUD(auth).list_crud(search=search_dict, order_by=order_by)
|
|
return [{{ table_name|snake_to_pascal_case }}OutSchema.model_validate(obj).model_dump() for obj in obj_list]
|
|
|
|
@classmethod
|
|
async def create_service(cls, auth: AuthSchema, data: {{ table_name|snake_to_pascal_case }}CreateSchema) -> Dict:
|
|
"""创建"""
|
|
obj = await {{ table_name|snake_to_pascal_case }}CRUD(auth).create_crud(data=data)
|
|
return {{ table_name|snake_to_pascal_case }}OutSchema.model_validate(obj).model_dump()
|
|
|
|
@classmethod
|
|
async def update_service(cls, auth: AuthSchema, id: int, data: {{ table_name|snake_to_pascal_case }}UpdateSchema) -> Dict:
|
|
"""更新"""
|
|
obj = await {{ table_name|snake_to_pascal_case }}CRUD(auth).get_by_id_crud(id=id)
|
|
if not obj:
|
|
raise CustomException(msg='更新失败,该数据不存在')
|
|
obj = await {{ table_name|snake_to_pascal_case }}CRUD(auth).update_crud(id=id, data=data)
|
|
return {{ table_name|snake_to_pascal_case }}OutSchema.model_validate(obj).model_dump()
|
|
|
|
@classmethod
|
|
async def delete_service(cls, auth: AuthSchema, ids: List[int]) -> None:
|
|
"""删除"""
|
|
if len(ids) < 1:
|
|
raise CustomException(msg='删除失败,删除对象不能为空')
|
|
for id in ids:
|
|
obj = await {{ table_name|snake_to_pascal_case }}CRUD(auth).get_by_id_crud(id=id)
|
|
if not obj:
|
|
raise CustomException(msg=f'删除失败,ID为{id}的数据不存在')
|
|
await {{ table_name|snake_to_pascal_case }}CRUD(auth).delete_crud(ids=ids)
|
|
|
|
@classmethod
|
|
async def set_available_service(cls, auth: AuthSchema, data: BatchSetAvailable) -> None:
|
|
"""批量设置状态"""
|
|
await {{ table_name|snake_to_pascal_case }}CRUD(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': '编号',
|
|
{% for column in columns %}
|
|
'{{ column.column_name }}': '{{ column.column_comment }}',
|
|
{% endfor %}
|
|
'created_at': '创建时间',
|
|
'updated_at': '更新时间',
|
|
'creator': '创建者',
|
|
}
|
|
|
|
data = obj_list.copy()
|
|
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:
|
|
"""批量导入"""
|
|
header_dict = {
|
|
{% for column in columns %}
|
|
'{{ column.column_comment }}': '{{ column.column_name }}',
|
|
{% endfor %}
|
|
}
|
|
|
|
try:
|
|
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)
|
|
|
|
error_msgs = []
|
|
success_count = 0
|
|
count = 0
|
|
|
|
for index, row in df.iterrows():
|
|
count += 1
|
|
try:
|
|
data = {
|
|
{% for column in columns %}
|
|
"{{ column.column_name }}": row['{{ column.column_name }}'],
|
|
{% endfor %}
|
|
}
|
|
await {{ table_name|snake_to_pascal_case }}CRUD(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:
|
|
logger.error(f"批量导入失败: {str(e)}")
|
|
raise CustomException(msg=f"导入失败: {str(e)}")
|
|
|
|
@classmethod
|
|
async def import_template_download_service(cls) -> bytes:
|
|
"""下载导入模板"""
|
|
header_list = [
|
|
{% for column in columns %}
|
|
'{{ column.column_comment }}',
|
|
{% endfor %}
|
|
]
|
|
return ExcelUtil.get_excel_template(
|
|
header_list=header_list,
|
|
selector_header_list=[],
|
|
option_list=[]
|
|
) |