perf: 优化代码生成功能

This commit is contained in:
insistence
2025-02-17 17:43:29 +08:00
parent 25e2a1e931
commit 2b474ddb35
11 changed files with 238 additions and 82 deletions

View File

@@ -67,7 +67,7 @@ async def import_gen_table(
@genController.put('', dependencies=[Depends(CheckUserInterfaceAuth('tool:gen:edit'))]) @genController.put('', dependencies=[Depends(CheckUserInterfaceAuth('tool:gen:edit'))])
@ValidateFields(validate_model='edit_post') @ValidateFields(validate_model='edit_gen_table')
@Log(title='代码生成', business_type=BusinessType.UPDATE) @Log(title='代码生成', business_type=BusinessType.UPDATE)
async def edit_gen_table( async def edit_gen_table(
request: Request, request: Request,

View File

@@ -5,6 +5,7 @@ from pydantic_validation_decorator import NotBlank
from typing import List, Literal, Optional from typing import List, Literal, Optional
from config.constant import GenConstant from config.constant import GenConstant
from module_admin.annotation.pydantic_annotation import as_query from module_admin.annotation.pydantic_annotation import as_query
from utils.string_util import StringUtil
class GenTableBaseModel(BaseModel): class GenTableBaseModel(BaseModel):
@@ -183,6 +184,8 @@ class GenTableColumnBaseModel(BaseModel):
sort: Optional[int] = Field(default=None, description='排序') sort: Optional[int] = Field(default=None, description='排序')
create_by: Optional[str] = Field(default=None, description='创建者') create_by: Optional[str] = Field(default=None, description='创建者')
create_time: Optional[datetime] = Field(default=None, description='创建时间') create_time: Optional[datetime] = Field(default=None, description='创建时间')
update_by: Optional[str] = Field(default=None, description='更新者')
update_time: Optional[datetime] = Field(default=None, description='更新时间')
@NotBlank(field_name='python_field', message='Python属性不能为空') @NotBlank(field_name='python_field', message='Python属性不能为空')
def get_python_field(self): def get_python_field(self):
@@ -198,15 +201,15 @@ class GenTableColumnModel(GenTableColumnBaseModel):
""" """
cap_python_field: Optional[str] = Field(default=None, description='字段大写形式') cap_python_field: Optional[str] = Field(default=None, description='字段大写形式')
pk: Optional[bool] = Field(default=None, description='是否为子表') pk: Optional[bool] = Field(default=None, description='是否主键')
increment: Optional[bool] = Field(default=None, description='是否为树表') increment: Optional[bool] = Field(default=None, description='是否自增')
required: Optional[bool] = Field(default=None, description='是否必填字段') required: Optional[bool] = Field(default=None, description='是否必填')
insert: Optional[bool] = Field(default=None, description='是否为必填字段') insert: Optional[bool] = Field(default=None, description='是否为插入字段')
edit: Optional[bool] = Field(default=None, description='是否为必填字段') edit: Optional[bool] = Field(default=None, description='是否编辑字段')
list: Optional[bool] = Field(default=None, description='是否为必填字段') list: Optional[bool] = Field(default=None, description='是否列表字段')
query: Optional[bool] = Field(default=None, description='是否为必填字段') query: Optional[bool] = Field(default=None, description='是否查询字段')
super_column: Optional[bool] = Field(default=None, description='是否为基类字段') super_column: Optional[bool] = Field(default=None, description='是否为基类字段')
usable_column: Optional[bool] = Field(default=None, description='是否为基类字段') usable_column: Optional[bool] = Field(default=None, description='是否为基类字段白名单')
@model_validator(mode='after') @model_validator(mode='after')
def check_some_is(self) -> 'GenTableModel': def check_some_is(self) -> 'GenTableModel':
@@ -220,19 +223,11 @@ class GenTableColumnModel(GenTableColumnBaseModel):
self.query = True if self.is_query and self.is_query == '1' else False self.query = True if self.is_query and self.is_query == '1' else False
self.super_column = ( self.super_column = (
True True
if any( if StringUtil.equals_any_ignore_case(self.python_field, GenConstant.TREE_ENTITY + GenConstant.BASE_ENTITY)
self.python_field and self.python_field.lower() == field.lower()
for field in GenConstant.TREE_ENTITY + GenConstant.BASE_ENTITY
)
else False else False
) )
self.usable_column = ( self.usable_column = (
True True if StringUtil.equals_any_ignore_case(self.python_field, ['parentId', 'orderNum', 'remark']) else False
if any(
self.python_field and self.python_field.lower() == field.lower()
for field in ['parentId', 'orderNum', 'remark']
)
else False
) )
return self return self

View File

@@ -3,6 +3,7 @@ import json
import os import os
import re import re
import zipfile import zipfile
from datetime import datetime
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from typing import List from typing import List
from config.constant import GenConstant from config.constant import GenConstant
@@ -121,6 +122,8 @@ class GenTableService:
edit_gen_table['options'] = json.dumps(edit_gen_table.get('params')) edit_gen_table['options'] = json.dumps(edit_gen_table.get('params'))
await GenTableDao.edit_gen_table_dao(query_db, edit_gen_table) await GenTableDao.edit_gen_table_dao(query_db, edit_gen_table)
for gen_table_column in page_object.columns: for gen_table_column in page_object.columns:
gen_table_column.update_by = page_object.update_by
gen_table_column.update_time = datetime.now()
await GenTableColumnDao.edit_gen_table_column_dao( await GenTableColumnDao.edit_gen_table_column_dao(
query_db, gen_table_column.model_dump(by_alias=True) query_db, gen_table_column.model_dump(by_alias=True)
) )
@@ -167,9 +170,9 @@ class GenTableService:
:return: 需要生成的业务表id对应的信息 :return: 需要生成的业务表id对应的信息
""" """
gen_table = await GenTableDao.get_gen_table_by_id(query_db, table_id) gen_table = await GenTableDao.get_gen_table_by_id(query_db, table_id)
await cls.set_table_from_options(GenTableModel(**CamelCaseUtil.transform_result(gen_table))) result = await cls.set_table_from_options(GenTableModel(**CamelCaseUtil.transform_result(gen_table)))
return gen_table return result
@classmethod @classmethod
async def get_gen_table_all_services(cls, query_db: AsyncSession): async def get_gen_table_all_services(cls, query_db: AsyncSession):
@@ -419,8 +422,8 @@ class GenTableService:
""" """
设置代码生成其他选项值 设置代码生成其他选项值
:param gen_table: 设置后的生成对象 :param gen_table: 生成对象
:return: :return: 设置后的生成对象
""" """
params_obj = json.loads(gen_table.options) if gen_table.options else None params_obj = json.loads(gen_table.options) if gen_table.options else None
if params_obj: if params_obj:
@@ -430,6 +433,8 @@ class GenTableService:
gen_table.parent_menu_id = params_obj.get(GenConstant.PARENT_MENU_ID) gen_table.parent_menu_id = params_obj.get(GenConstant.PARENT_MENU_ID)
gen_table.parent_menu_name = params_obj.get(GenConstant.PARENT_MENU_NAME) gen_table.parent_menu_name = params_obj.get(GenConstant.PARENT_MENU_NAME)
return gen_table
@classmethod @classmethod
async def validate_edit(cls, edit_gen_table: EditGenTableModel): async def validate_edit(cls, edit_gen_table: EditGenTableModel):
""" """
@@ -438,19 +443,19 @@ class GenTableService:
:param edit_gen_table: 编辑业务表对象 :param edit_gen_table: 编辑业务表对象
""" """
if edit_gen_table.tpl_category == GenConstant.TPL_TREE: if edit_gen_table.tpl_category == GenConstant.TPL_TREE:
params_obj = edit_gen_table.params params_obj = edit_gen_table.params.model_dump(by_alias=True)
if not getattr(params_obj, GenConstant.TREE_CODE): if GenConstant.TREE_CODE not in params_obj:
raise ServiceException('树编码字段不能为空') raise ServiceException(message='树编码字段不能为空')
elif not getattr(params_obj, GenConstant.TREE_PARENT_CODE): elif GenConstant.TREE_PARENT_CODE not in params_obj:
raise ServiceException('树父编码字段不能为空') raise ServiceException(message='树父编码字段不能为空')
elif not getattr(params_obj, GenConstant.TREE_NAME): elif GenConstant.TREE_NAME not in params_obj:
raise ServiceException('树名称字段不能为空') raise ServiceException(message='树名称字段不能为空')
elif edit_gen_table.tpl_category == GenConstant.TPL_SUB: elif edit_gen_table.tpl_category == GenConstant.TPL_SUB:
if not edit_gen_table.sub_table_name: if not edit_gen_table.sub_table_name:
raise ServiceException('关联子表的表名不能为空') raise ServiceException(message='关联子表的表名不能为空')
elif not edit_gen_table.sub_table_fk_name: elif not edit_gen_table.sub_table_fk_name:
raise ServiceException('子表关联的外键名不能为空') raise ServiceException(message='子表关联的外键名不能为空')
class GenTableColumnService: class GenTableColumnService:

View File

@@ -119,7 +119,7 @@ async def export_{{ moduleName }}_{{ businessName }}_list(
): ):
# 获取全量数据 # 获取全量数据
{{ businessName }}_query_result = await {{ BusinessName }}Service.get_{{ businessName }}_list_services(query_db, {{ businessName }}_page_query, is_page=False) {{ businessName }}_query_result = await {{ BusinessName }}Service.get_{{ businessName }}_list_services(query_db, {{ businessName }}_page_query, is_page=False)
{{ businessName }}_export_result = await {{ BusinessName }}Service.export_{{ businessName }}_list_services({{ businessName }}_query_result) {{ businessName }}_export_result = await {{ BusinessName }}Service.export_{{ businessName }}_list_services({% if dicts %}request, {% endif %}{{ businessName }}_query_result)
logger.info('导出成功') logger.info('导出成功')
return ResponseUtil.streaming(data=bytes2file_response({{ businessName }}_export_result)) return ResponseUtil.streaming(data=bytes2file_response({{ businessName }}_export_result))

View File

@@ -2,7 +2,11 @@
{% set pk_field = pkColumn.python_field | camel_to_snake %} {% set pk_field = pkColumn.python_field | camel_to_snake %}
{% set pkParentheseIndex = pkColumn.column_comment.find("") %} {% set pkParentheseIndex = pkColumn.column_comment.find("") %}
{% set pk_field_comment = pkColumn.column_comment[:pkParentheseIndex] if pkParentheseIndex != -1 else pkColumn.column_comment %} {% set pk_field_comment = pkColumn.column_comment[:pkParentheseIndex] if pkParentheseIndex != -1 else pkColumn.column_comment %}
{% for column in columns %}
{% if column.python_field == "createTime" %}
from datetime import datetime, time from datetime import datetime, time
{% endif %}
{% endfor %}
from sqlalchemy import delete, select, update from sqlalchemy import delete, select, update
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
{% if table.sub %} {% if table.sub %}
@@ -27,7 +31,23 @@ class {{ BusinessName }}Dao:
:param {{ pk_field }}: {{ pk_field_comment }} :param {{ pk_field }}: {{ pk_field_comment }}
:return: {{ functionName }}信息对象 :return: {{ functionName }}信息对象
""" """
{{ businessName }}_info = (await db.execute(select({{ ClassName }}).where({{ ClassName }}.{{ pk_field }} == {{ pk_field }}))).scalars().first() {{ businessName }}_info = (
(
await db.execute(
{% if table.sub %}
select({{ ClassName }})
.options(selectinload({{ ClassName }}.{{ subclassName }}_list))
{% else %}
select({{ ClassName }})
{% endif %}
.where(
{{ ClassName }}.{{ pk_field }} == {{ pk_field }}
)
)
)
.scalars()
.first()
)
return {{ businessName }}_info return {{ businessName }}_info
@@ -69,9 +89,9 @@ class {{ BusinessName }}Dao:
:return: {{ functionName }}列表信息对象 :return: {{ functionName }}列表信息对象
""" """
query = ( query = (
{% if table.sub %%} {% if table.sub %}
select({{ ClassName }}) select({{ ClassName }})
.options(selectinload{{ ClassName }}.{{ subTable.business_name }}) .options(selectinload({{ ClassName }}.{{ subclassName }}_list))
{% else %} {% else %}
select({{ ClassName }}) select({{ ClassName }})
{% endif %} {% endif %}
@@ -117,10 +137,10 @@ class {{ BusinessName }}Dao:
新增{{ functionName }}数据库操作 新增{{ functionName }}数据库操作
:param db: orm对象 :param db: orm对象
:param notice: {{ functionName }}对象 :param {{ businessName }}: {{ functionName }}对象
:return: :return:
""" """
db_{{ businessName }} = {{ ClassName }}(**{{ businessName }}.model_dump()) db_{{ businessName }} = {{ ClassName }}(**{{ businessName }}.model_dump({%if table.sub %}exclude={'{{ subclassName }}_list'}{% endif %}))
db.add(db_{{ businessName }}) db.add(db_{{ businessName }})
await db.flush() await db.flush()
@@ -132,7 +152,7 @@ class {{ BusinessName }}Dao:
编辑{{ functionName }}数据库操作 编辑{{ functionName }}数据库操作
:param db: orm对象 :param db: orm对象
:param notice: 需要更新的{{ functionName }}字典 :param {{ businessName }}: 需要更新的{{ functionName }}字典
:return: :return:
""" """
await db.execute(update({{ ClassName }}), [{{ businessName }}]) await db.execute(update({{ ClassName }}), [{{ businessName }}])
@@ -143,7 +163,46 @@ class {{ BusinessName }}Dao:
删除{{ functionName }}数据库操作 删除{{ functionName }}数据库操作
:param db: orm对象 :param db: orm对象
:param notice: {{ functionName }}对象 :param {{ businessName }}: {{ functionName }}对象
:return: :return:
""" """
await db.execute(delete({{ ClassName }}).where({{ ClassName }}.{{ pk_field }}.in_([{{ businessName }}.{{ pk_field }}]))) await db.execute(delete({{ ClassName }}).where({{ ClassName }}.{{ pk_field }}.in_([{{ businessName }}.{{ pk_field }}])))
{% if table.sub %}
@classmethod
async def add_{{ subTable.business_name }}_dao(cls, db: AsyncSession, {{ subTable.business_name }}: {{ subTable.business_name | capitalize }}Model):
"""
新增{{ subTable.function_name }}数据库操作
:param db: orm对象
:param {{ subTable.business_name }}: {{ subTable.function_name }}对象
:return:
"""
db_{{ subTable.business_name }} = {{ subClassName }}(**{{ subTable.business_name }}.model_dump())
db.add(db_{{ subTable.business_name }})
await db.flush()
return db_{{ subTable.business_name }}
@classmethod
async def edit_{{ subTable.business_name }}_dao(cls, db: AsyncSession, {{ subTable.business_name }}: dict):
"""
编辑{{ subTable.function_name }}数据库操作
:param db: orm对象
:param {{ subTable.business_name }}: 需要更新的{{ subTable.function_name }}字典
:return:
"""
await db.execute(update({{ subClassName }}), [{{ subTable.business_name }}])
@classmethod
async def delete_{{ subTable.business_name }}_dao(cls, db: AsyncSession, {{ subTable.business_name }}: {{ subTable.business_name | capitalize }}Model):
"""
删除{{ subTable.function_name }}数据库操作
:param db: orm对象
:param {{ subTable.business_name }}: {{ subTable.function_name }}对象
:return:
"""
await db.execute(delete({{ subClassName }}).where({{ subClassName }}.{{ subTable.pk_column.python_field | camel_to_snake }}.in_([{{ subTable.business_name }}.{{ subTable.pk_column.python_field | camel_to_snake }}])))
{% endif %}

View File

@@ -19,12 +19,12 @@ class {{ ClassName }}(Base):
{% endfor %} {% endfor %}
{% if table.sub %} {% if table.sub %}
{{ subTable.business_name }} = relationship('{{ subTable.class_name }}', back_populates='{{ businessName }}') {{ subclassName }}_list = relationship('{{ subClassName }}', back_populates='{{ businessName }}')
{% endif %} {% endif %}
{% if table.sub %} {% if table.sub %}
class {{ subTable.class_name }}(Base): class {{ subClassName }}(Base):
""" """
{{ subTable.function_name }}表 {{ subTable.function_name }}表
""" """
@@ -36,6 +36,6 @@ class {{ subTable.class_name }}(Base):
{% endfor %} {% endfor %}
{% if table.sub %} {% if table.sub %}
{{ businessName }} = relationship('{{ ClassName }}', back_populates='{{ subTable.business_name }}') {{ businessName }} = relationship('{{ ClassName }}', back_populates='{{ subclassName }}_list')
{% endif %} {% endif %}
{% endif %} {% endif %}

View File

@@ -2,12 +2,18 @@
{% set pk_field = pkColumn.python_field | camel_to_snake %} {% set pk_field = pkColumn.python_field | camel_to_snake %}
{% set pkParentheseIndex = pkColumn.column_comment.find("") %} {% set pkParentheseIndex = pkColumn.column_comment.find("") %}
{% set pk_field_comment = pkColumn.column_comment[:pkParentheseIndex] if pkParentheseIndex != -1 else pkColumn.column_comment %} {% set pk_field_comment = pkColumn.column_comment[:pkParentheseIndex] if pkParentheseIndex != -1 else pkColumn.column_comment %}
{% if dicts %}
from fastapi import Request
{% endif %}
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from typing import List from typing import List
from config.constant import CommonConstant from config.constant import CommonConstant
from exceptions.exception import ServiceException from exceptions.exception import ServiceException
from {{ packageName }}.dao.{{ businessName }}_dao import {{ BusinessName }}Dao
from module_admin.entity.vo.common_vo import CrudResponseModel from module_admin.entity.vo.common_vo import CrudResponseModel
{% if dicts %}
from module_admin.service.dict_service import DictDataService
{% endif %}
from {{ packageName }}.dao.{{ businessName }}_dao import {{ BusinessName }}Dao
from {{ packageName }}.entity.vo.{{ businessName }}_vo import Delete{{ BusinessName }}Model, {{ BusinessName }}Model, {{ BusinessName }}PageQueryModel from {{ packageName }}.entity.vo.{{ businessName }}_vo import Delete{{ BusinessName }}Model, {{ BusinessName }}Model, {{ BusinessName }}PageQueryModel
from utils.common_util import CamelCaseUtil from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil from utils.excel_util import ExcelUtil
@@ -65,18 +71,28 @@ class {{ BusinessName }}Service:
:param page_object: 新增{{ functionName }}对象 :param page_object: 新增{{ functionName }}对象
:return: 新增{{ functionName }}校验结果 :return: 新增{{ functionName }}校验结果
""" """
if not await cls.check_post_name_unique_services(query_db, page_object): {% for column in columns %}
raise ServiceException(message=f'新增岗位{page_object.post_name}失败,岗位名称已存在') {% set parentheseIndex = column.column_comment.find("") %}
elif not await cls.check_post_code_unique_services(query_db, page_object): {% set comment = column.column_comment[:parentheseIndex] if parentheseIndex != -1 else column.column_comment %}
raise ServiceException(message=f'新增岗位{page_object.post_name}失败,岗位编码已存在') {% if column.required %}
else: if not await cls.check_{{ column.python_field | camel_to_snake }}_unique_services(query_db, page_object)
try: raise ServiceException(message=f'新增{{ functionName }}{page_object.{{ column.python_field | camel_to_snake }}}失败,{{ comment }}已存在')
await {{ BusinessName }}Dao.add_{{ businessName }}_dao(query_db, page_object) {% endif %}
await query_db.commit() {% endfor %}
return CrudResponseModel(is_success=True, message='新增成功') try:
except Exception as e: {% if table.sub %}
await query_db.rollback() add_{{ businessName }} = await {{ BusinessName }}Dao.add_{{ businessName }}_dao(query_db, page_object)
raise e if add_{{ businessName }}:
for sub_table in page_object.{{ subclassName }}_list:
await {{ BusinessName }}Dao.add_{{ subTable.business_name }}_dao(query_db, sub_table)
{% else %}
await {{ BusinessName }}Dao.add_{{ businessName }}_dao(query_db, page_object)
{% endif %}
await query_db.commit()
return CrudResponseModel(is_success=True, message='新增成功')
except Exception as e:
await query_db.rollback()
raise e
@classmethod @classmethod
async def edit_{{ businessName }}_services(cls, query_db: AsyncSession, page_object: {{ BusinessName }}Model): async def edit_{{ businessName }}_services(cls, query_db: AsyncSession, page_object: {{ BusinessName }}Model):
@@ -87,21 +103,28 @@ class {{ BusinessName }}Service:
:param page_object: 编辑{{ functionName }}对象 :param page_object: 编辑{{ functionName }}对象
:return: 编辑{{ functionName }}校验结果 :return: 编辑{{ functionName }}校验结果
""" """
edit_{{ businessName }} = page_object.model_dump(exclude_unset=True) edit_{{ businessName }} = page_object.model_dump(exclude_unset=True{% if table.sub %}, exclude={'{{ subclassName }}_list'}{% endif %})
{{ businessName }}_info = await cls.{{ businessName }}_detail_services(query_db, page_object.{{ pk_field }}) {{ businessName }}_info = await cls.{{ businessName }}_detail_services(query_db, page_object.{{ pk_field }})
if {{ businessName }}_info.{{ pk_field }}: if {{ businessName }}_info.{{ pk_field }}:
if not await cls.check_post_name_unique_services(query_db, page_object): {% for column in columns %}
raise ServiceException(message=f'修改岗位{page_object.post_name}失败,岗位名称已存在') {% set parentheseIndex = column.column_comment.find("") %}
elif not await cls.check_post_code_unique_services(query_db, page_object): {% set comment = column.column_comment[:parentheseIndex] if parentheseIndex != -1 else column.column_comment %}
raise ServiceException(message=f'修改岗位{page_object.post_name}失败,岗位编码已存在') {% if column.required %}
else: if not await cls.check_{{ column.python_field | camel_to_snake }}_unique_services(query_db, page_object)
try: raise ServiceException(message=f'修改{{ functionName }}{page_object.{{ column.python_field | camel_to_snake }}}失败,{{ comment }}已存在')
await {{ BusinessName }}Dao.edit_{{ businessName }}_dao(query_db, edit_{{ businessName }}) {% endif %}
await query_db.commit() {% endfor %}
return CrudResponseModel(is_success=True, message='更新成功') try:
except Exception as e: await {{ BusinessName }}Dao.edit_{{ businessName }}_dao(query_db, edit_{{ businessName }})
await query_db.rollback() {% if table.sub %}
raise e for sub_table in page_object.{{ subclassName }}_list:
await {{ BusinessName }}Dao.edit_{{ subTable.business_name }}_dao(query_db, sub_table)
{% endif %}
await query_db.commit()
return CrudResponseModel(is_success=True, message='更新成功')
except Exception as e:
await query_db.rollback()
raise e
else: else:
raise ServiceException(message='{{ functionName }}不存在') raise ServiceException(message='{{ functionName }}不存在')
@@ -118,8 +141,12 @@ class {{ BusinessName }}Service:
{{ pk_field }}_list = page_object.{{ pk_field }}s.split(',') {{ pk_field }}_list = page_object.{{ pk_field }}s.split(',')
try: try:
for {{ pk_field }} in {{ pk_field }}_list: for {{ pk_field }} in {{ pk_field }}_list:
{{ businessName }} = await cls.{{ businessName }}_detail_services(query_db, int({{ pk_field }}))
await {{ BusinessName }}Dao.delete_{{ businessName }}_dao(query_db, {{ BusinessName }}Model({{ pkField }}={{ pk_field }})) await {{ BusinessName }}Dao.delete_{{ businessName }}_dao(query_db, {{ BusinessName }}Model({{ pkField }}={{ pk_field }}))
{% if table.sub %}
{{ businessName }} = await cls.{{ businessName }}_detail_services(query_db, int({{ pk_field }}))
for sub_table in {{ businessName }}.{{ subclassName }}_list:
await {{ BusinessName }}Dao.delete_{{ subTable.business_name }}_dao(query_db, sub_table)
{% endif %}
await query_db.commit() await query_db.commit()
return CrudResponseModel(is_success=True, message='删除成功') return CrudResponseModel(is_success=True, message='删除成功')
except Exception as e: except Exception as e:
@@ -146,7 +173,7 @@ class {{ BusinessName }}Service:
return result return result
@staticmethod @staticmethod
async def export_{{ businessName }}_list_services({{ businessName }}_list: List): async def export_{{ businessName }}_list_services({% if dicts %}request: Request, {% endif %}{{ businessName }}_list: List):
""" """
导出{{ functionName }}信息service 导出{{ functionName }}信息service
@@ -161,12 +188,22 @@ class {{ BusinessName }}Service:
'{{ column.python_field }}': '{{ comment }}', '{{ column.python_field }}': '{{ comment }}',
{% endfor %} {% endfor %}
} }
{% if dicts %}
{% for dict_type in dicts.split(", ") %}
{{ dict_type[1:-1] }}_list = await DictDataService.query_dict_data_list_from_cache_services(
request.app.state.redis, dict_type={{ dict_type }}
)
{{ dict_type[1:-1] }}_option = [dict(label=item.get('dictLabel'), value=item.get('dictValue')) for item in {{ dict_type[1:-1] }}_list]
{{ dict_type[1:-1] }}_option_dict = {item.get('value'): item for item in {{ dict_type[1:-1] }}_option}
{% endfor %}
for item in {{ businessName }}_list: for item in {{ businessName }}_list:
if item.get('status') == '0': {% for column in columns %}
item['status'] = '正常' {% if column.dict_type %}
else: if str(item.get('{{ column.python_field }}')) in {{ column.dict_type }}_option_dict.keys():
item['status'] = '停用' item['{{ column.python_field }}'] = {{ column.dict_type }}_option_dict.get(str(item.get('{{ column.python_field }}'))).get('label')
{% endif %}
{% endfor %}
{% endif %}
binary_data = ExcelUtil.export_list2excel({{ businessName }}_list, mapping_dict) binary_data = ExcelUtil.export_list2excel({{ businessName }}_list, mapping_dict)
return binary_data return binary_data

View File

@@ -2,13 +2,33 @@
{% set pk_field = pkColumn.python_field | camel_to_snake %} {% set pk_field = pkColumn.python_field | camel_to_snake %}
{% set pkParentheseIndex = pkColumn.column_comment.find("") %} {% set pkParentheseIndex = pkColumn.column_comment.find("") %}
{% set pk_field_comment = pkColumn.column_comment[:pkParentheseIndex] if pkParentheseIndex != -1 else pkColumn.column_comment %} {% set pk_field_comment = pkColumn.column_comment[:pkParentheseIndex] if pkParentheseIndex != -1 else pkColumn.column_comment %}
{% set vo_field_required = namespace(has_required=False) %}
{% for column in columns %}
{% if column.required %}
{% set vo_field_required.has_required = True %}
{% endif %}
{% endfor %}
{% if table.sub %}
{% set sub_vo_field_required = namespace(has_required=False) %}
{% for sub_column in subTable.columns %}
{% if sub_column.required %}
{% set sub_vo_field_required.has_required = True %}
{% endif %}
{% endfor %}
{% endif %}
{% for vo_import in voImportList %} {% for vo_import in voImportList %}
{{ vo_import }} {{ vo_import }}
{% endfor %} {% endfor %}
from pydantic import BaseModel, ConfigDict, Field from pydantic import BaseModel, ConfigDict, Field
from pydantic.alias_generators import to_camel from pydantic.alias_generators import to_camel
{% if vo_field_required.has_required %}
from pydantic_validation_decorator import NotBlank from pydantic_validation_decorator import NotBlank
{% endif %}
{% if table.sub %}
from typing import List, Optional
{% else %}
from typing import Optional from typing import Optional
{% endif %}
from module_admin.annotation.pydantic_annotation import as_query from module_admin.annotation.pydantic_annotation import as_query
@@ -22,6 +42,9 @@ class {{ BusinessName }}Model(BaseModel):
{% for column in columns %} {% for column in columns %}
{{ column.column_name }}: Optional[{{ column.python_type }}] = Field(default=None, description='{{ column.column_comment }}') {{ column.column_name }}: Optional[{{ column.python_type }}] = Field(default=None, description='{{ column.column_comment }}')
{% endfor %} {% endfor %}
{% if table.sub %}
{{ subclassName }}_list: Optional[List['{{ subTable.business_name | capitalize }}Model']] = Field(default=None, description='子表列信息')
{% endif %}
{% for column in columns %} {% for column in columns %}
{% if column.required %} {% if column.required %}
@@ -33,19 +56,49 @@ class {{ BusinessName }}Model(BaseModel):
{% endif %} {% endif %}
{% endfor %} {% endfor %}
{% if vo_field_required.has_required %}
def validate_fields(self): def validate_fields(self):
{% set vo_field_required = namespace(has_required=False) %}
{% for column in columns %} {% for column in columns %}
{% if column.required %} {% if column.required %}
self.get_{{ column.column_name }}() self.get_{{ column.column_name }}()
{% set vo_field_required.has_required = True %}
{% endif %} {% endif %}
{% endfor %} {% endfor %}
{% if not vo_field_required.has_required %}
pass
{% endif %} {% endif %}
{% if table.sub %}
class {{ subTable.business_name | capitalize }}Model(BaseModel):
"""
{{ subTable.function_name }}表对应pydantic模型
"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
{% for sub_column in subTable.columns %}
{{ sub_column.column_name }}: Optional[{{ sub_column.python_type }}] = Field(default=None, description='{{ sub_column.column_comment}}')
{% endfor %}
{% for sub_column in subTable.columns %}
{% if sub_column.required %}
{% set parentheseIndex = sub_column.column_comment.find("") %}
{% set comment = sub_column.column_comment[:parentheseIndex] if parentheseIndex != -1 else sub_column.column_comment %}
@NotBlank(field_name='{{ sub_column.column_name }}', message='{{ comment }}不能为空')
def get_{{ sub_column.column_name }}(self):
return self.{{ sub_column.column_name }}
{% endif %}
{% endfor %}
{% if sub_vo_field_required.has_required %}
def validate_fields(self):
{% for sub_column in subTable.columns %}
{% if sub_column.required %}
self.get_{{ sub_column.column_name }}()
{% endif %}
{% endfor %}
{% endif %}
{% endif %}
class {{ BusinessName }}QueryModel({{ BusinessName }}Model): class {{ BusinessName }}QueryModel({{ BusinessName }}Model):
""" """
{{ functionName }}不分页查询模型 {{ functionName }}不分页查询模型

View File

@@ -127,6 +127,7 @@
{% else %} {% else %}
<el-table-column label="{{ comment }}" align="center" prop="{{ pythonField }}" /> <el-table-column label="{{ comment }}" align="center" prop="{{ pythonField }}" />
{% endif %} {% endif %}
{% endif %}
{% endfor %} {% endfor %}
<el-table-column label="操作" align="center" class-name="small-padding fixed-width"> <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template slot-scope="scope"> <template slot-scope="scope">
@@ -135,7 +136,7 @@
type="text" type="text"
icon="el-icon-edit" icon="el-icon-edit"
@click="handleUpdate(scope.row)" @click="handleUpdate(scope.row)"
v-hasPermi="['{{ moduleName }:{{ businessName }}:edit']" v-hasPermi="['{{ moduleName }}:{{ businessName }}:edit']"
>修改</el-button> >修改</el-button>
<el-button <el-button
size="mini" size="mini"

View File

@@ -98,6 +98,11 @@ class GenUtils:
# 内容字段设置富文本控件 # 内容字段设置富文本控件
elif column_name.lower().endswith('content'): elif column_name.lower().endswith('content'):
column.html_type = GenConstant.HTML_EDITOR column.html_type = GenConstant.HTML_EDITOR
column.create_by = table.create_by
column.create_time = datetime.now()
column.update_by = table.update_by
column.update_time = datetime.now()
@classmethod @classmethod
def arrays_contains(cls, arr: List[str], target_value: str) -> bool: def arrays_contains(cls, arr: List[str], target_value: str) -> bool:

View File

@@ -256,6 +256,7 @@ class TemplateUtils:
""" """
columns = gen_table.columns or [] columns = gen_table.columns or []
import_list = set() import_list = set()
import_list.add('from sqlalchemy import Column')
for column in columns: for column in columns:
data_type = cls.get_db_type(column.column_type) data_type = cls.get_db_type(column.column_type)
import_list.add( import_list.add(
@@ -332,7 +333,7 @@ class TemplateUtils:
""" """
for column in columns: for column in columns:
if ( if (
column.super_column not column.super_column
and StringUtil.is_not_empty(column.dict_type) and StringUtil.is_not_empty(column.dict_type)
and StringUtil.equals_any_ignore_case( and StringUtil.equals_any_ignore_case(
column.html_type, [GenConstant.HTML_SELECT, GenConstant.HTML_RADIO, GenConstant.HTML_CHECKBOX] column.html_type, [GenConstant.HTML_SELECT, GenConstant.HTML_RADIO, GenConstant.HTML_CHECKBOX]