Skip to content

Commit 6c70b34

Browse files
authored
Optimize the file structure of code generator (#574)
1 parent 960d9f6 commit 6c70b34

File tree

14 files changed

+69
-59
lines changed

14 files changed

+69
-59
lines changed

backend/app/generator/conf.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,6 @@
88
class GeneratorSettings(BaseSettings):
99
"""代码生成配置"""
1010

11-
# 模版
12-
TEMPLATE_BACKEND_DIR_NAME: str = 'py'
13-
1411
# 代码下载
1512
DOWNLOAD_ZIP_FILENAME: str = 'fba_generator'
1613

backend/app/generator/schema/gen.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@ class ImportParam(SchemaBase):
99
"""导入参数"""
1010

1111
app: str = Field(description='应用名称,用于代码生成到指定 app')
12-
table_name: str = Field(description='数据库表名')
1312
table_schema: str = Field(description='数据库名')
13+
table_name: str = Field(description='数据库表名')

backend/app/generator/schema/gen_model.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from pydantic import ConfigDict, Field, field_validator
44

55
from backend.common.schema import SchemaBase
6-
from backend.utils.type_conversion import sql_type_to_sqlalchemy
6+
from backend.utils.generator.type_conversion import sql_type_to_sqlalchemy
77

88

99
class GenModelSchemaBase(SchemaBase):

backend/app/generator/service/gen_model_service.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from backend.common.enums import GenModelMySQLColumnType
99
from backend.common.exception import errors
1010
from backend.database.db import async_db_session
11-
from backend.utils.type_conversion import sql_type_to_pydantic
11+
from backend.utils.generator.type_conversion import sql_type_to_pydantic
1212

1313

1414
class GenModelService:

backend/app/generator/service/gen_service.py

Lines changed: 48 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@
2121
from backend.common.exception import errors
2222
from backend.core.path_conf import BASE_PATH
2323
from backend.database.db import async_db_session
24-
from backend.utils.gen_template import gen_template
25-
from backend.utils.type_conversion import sql_type_to_pydantic
24+
from backend.utils.generator.gen_template import gen_template
25+
from backend.utils.generator.type_conversion import sql_type_to_pydantic
2626

2727

2828
class GenService:
@@ -99,7 +99,7 @@ async def render_tpl_code(*, business: GenBusiness) -> dict[str, str]:
9999
gen_vars = gen_template.get_vars(business, gen_models)
100100
return {
101101
tpl_path: await gen_template.get_template(tpl_path).render_async(**gen_vars)
102-
for tpl_path in gen_template.get_template_paths()
102+
for tpl_path in gen_template.get_template_files()
103103
}
104104

105105
async def preview(self, *, pk: int) -> dict[str, bytes]:
@@ -115,10 +115,13 @@ async def preview(self, *, pk: int) -> dict[str, bytes]:
115115
raise errors.NotFoundError(msg='业务不存在')
116116

117117
tpl_code_map = await self.render_tpl_code(business=business)
118-
return {
119-
tpl.replace('.jinja', '.py') if tpl.startswith('py') else ...: code.encode('utf-8')
120-
for tpl, code in tpl_code_map.items()
121-
}
118+
119+
codes = {}
120+
for tpl, code in tpl_code_map.items():
121+
if tpl.startswith('python'):
122+
codes[tpl.replace('.jinja', '.py').split('/')[-1]] = code.encode('utf-8')
123+
124+
return codes
122125

123126
@staticmethod
124127
async def get_generate_path(*, pk: int) -> list[str]:
@@ -133,9 +136,10 @@ async def get_generate_path(*, pk: int) -> list[str]:
133136
if not business:
134137
raise errors.NotFoundError(msg='业务不存在')
135138

136-
gen_path = business.gen_path or 'fba-backend-app-path'
139+
gen_path = business.gen_path or 'fba-backend-app-dir'
137140
target_files = gen_template.get_code_gen_paths(business)
138-
return [os.path.join(gen_path, *target_file.split('/')[1:]) for target_file in target_files]
141+
142+
return [os.path.join(gen_path, *target_file.split('/')) for target_file in target_files]
139143

140144
async def generate(self, *, pk: int) -> None:
141145
"""
@@ -155,32 +159,29 @@ async def generate(self, *, pk: int) -> None:
155159
for tpl_path, code in tpl_code_map.items():
156160
code_filepath = os.path.join(
157161
gen_path,
158-
*gen_template.get_code_gen_path(tpl_path, business).split('/')[1:],
162+
*gen_template.get_code_gen_path(tpl_path, business).split('/'),
159163
)
160-
code_folder = Path(str(code_filepath)).parent
161-
code_folder.mkdir(parents=True, exist_ok=True)
162164

163165
# 写入 init 文件
166+
str_code_filepath = str(code_filepath)
167+
code_folder = Path(str_code_filepath).parent
168+
code_folder.mkdir(parents=True, exist_ok=True)
169+
164170
init_filepath = code_folder.joinpath('__init__.py')
165-
if not init_filepath.exists():
166-
async with aiofiles.open(init_filepath, 'w', encoding='utf-8') as f:
167-
await f.write(gen_template.init_content)
171+
async with aiofiles.open(init_filepath, 'w', encoding='utf-8') as f:
172+
await f.write(gen_template.init_content)
168173

169-
if 'api' in str(code_folder):
170-
# api __init__.py
174+
# api __init__.py
175+
if 'api' in str_code_filepath:
171176
api_init_filepath = code_folder.parent.joinpath('__init__.py')
172-
if not api_init_filepath.exists():
173-
async with aiofiles.open(api_init_filepath, 'w', encoding='utf-8') as f:
174-
await f.write(gen_template.init_content)
175-
# app __init__.py
176-
app_init_filepath = api_init_filepath.parent.joinpath('__init__.py')
177-
if not app_init_filepath.exists():
178-
async with aiofiles.open(app_init_filepath, 'w', encoding='utf-8') as f:
179-
await f.write(gen_template.init_content)
177+
async with aiofiles.open(api_init_filepath, 'w', encoding='utf-8') as f:
178+
await f.write(gen_template.init_content)
180179

181-
# 写入代码文件
182-
async with aiofiles.open(code_filepath, 'w', encoding='utf-8') as f:
183-
await f.write(code)
180+
# app __init__.py
181+
if 'service' in str_code_filepath:
182+
app_init_filepath = code_folder.parent.joinpath('__init__.py')
183+
async with aiofiles.open(app_init_filepath, 'w', encoding='utf-8') as f:
184+
await f.write(gen_template.init_content)
184185

185186
# model init 文件补充
186187
if code_folder.name == 'model':
@@ -190,6 +191,10 @@ async def generate(self, *, pk: int) -> None:
190191
f'import {to_pascal(business.table_name_en)}\n',
191192
)
192193

194+
# 写入代码文件
195+
async with aiofiles.open(code_filepath, 'w', encoding='utf-8') as f:
196+
await f.write(code)
197+
193198
async def download(self, *, pk: int) -> io.BytesIO:
194199
"""
195200
下载生成的代码
@@ -206,13 +211,12 @@ async def download(self, *, pk: int) -> io.BytesIO:
206211
with zipfile.ZipFile(bio, 'w') as zf:
207212
tpl_code_map = await self.render_tpl_code(business=business)
208213
for tpl_path, code in tpl_code_map.items():
209-
# 写入代码文件
210-
new_code_path = gen_template.get_code_gen_path(tpl_path, business)
211-
zf.writestr(new_code_path, code)
214+
code_filepath = gen_template.get_code_gen_path(tpl_path, business)
212215

213216
# 写入 init 文件
214-
init_filepath = os.path.join(*new_code_path.split('/')[:-1], '__init__.py')
215-
if 'model' not in new_code_path.split('/'):
217+
code_dir = os.path.dirname(code_filepath)
218+
init_filepath = os.path.join(code_dir, '__init__.py')
219+
if 'model' not in code_filepath.split('/'):
216220
zf.writestr(init_filepath, gen_template.init_content)
217221
else:
218222
zf.writestr(
@@ -222,11 +226,19 @@ async def download(self, *, pk: int) -> io.BytesIO:
222226
f'import {to_pascal(business.table_name_en)}\n',
223227
)
224228

225-
if 'api' in new_code_path:
226-
# api __init__.py
227-
api_init_filepath = os.path.join(*new_code_path.split('/')[:-2], '__init__.py')
229+
# api __init__.py
230+
if 'api' in code_dir:
231+
api_init_filepath = os.path.join(os.path.dirname(code_dir), '__init__.py')
228232
zf.writestr(api_init_filepath, gen_template.init_content)
229233

234+
# app __init__.py
235+
if 'service' in code_dir:
236+
app_init_filepath = os.path.join(os.path.dirname(code_dir), '__init__.py')
237+
zf.writestr(app_init_filepath, gen_template.init_content)
238+
239+
# 写入代码文件
240+
zf.writestr(code_filepath, code)
241+
230242
bio.seek(0)
231243
return bio
232244

backend/core/path_conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
UPLOAD_DIR = STATIC_DIR / 'upload'
1919

2020
# jinja2 模版文件路径
21-
JINJA2_TEMPLATE_DIR = BASE_PATH / 'templates'
21+
JINJA2_TEMPLATE_DIR = BASE_PATH / 'templates' / 'generator'
2222

2323
# 插件目录
2424
PLUGIN_DIR = BASE_PATH / 'plugin'

0 commit comments

Comments
 (0)