-
Notifications
You must be signed in to change notification settings - Fork 6
/
codegen.py
488 lines (399 loc) · 14 KB
/
codegen.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import sys
import argparse
from sqlalchemy.schema import MetaData
from sqlalchemy.engine import create_engine
from sqlacodegen.codegen import CodeGenerator
from tornado.options import define
abs_file = os.path.abspath(sys.argv[0])
ROOT_PATH = abs_file[:abs_file.rfind('/')]
define('ROOT_PATH', ROOT_PATH)
sys.path.insert(0, '/Users/leeyi/workspace/py3/trest')
from trest.utils import func
from trest.db.dbalchemy import DBConfigParser
class ModelGenerator(CodeGenerator):
template = '''\
#!/usr/bin/env python
# -*- coding: utf-8 -*-
{imports}
from trest.db import Model as Base
{models}
'''
def render(self, outfile):
rendered_models = []
for model in self.models:
if isinstance(model, self.class_model):
rendered_models.append(self.render_class(model))
elif isinstance(model, self.table_model):
rendered_models.append(self.render_table(model))
imports = self.render_imports()
imports = imports.replace('from sqlalchemy.ext.declarative import declarative_base', '')
output = self.template.format(
imports=imports,
metadata_declarations=self.render_metadata_declarations(),
models=self.model_separator.join(rendered_models).rstrip('\n'))
# print(output, file=outfile)
fout = open(outfile, 'w', encoding='utf8')
# 写入文件内容
fout.write(output)
# 关闭文件
fout.close()
class ServiceGenerator:
template = '''\
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from trest.utils import utime
from trest.logger import SysLogger
from trest.config import settings
from trest.exception import JsonError
from applications.common.models.{classname_underline} import {classname}
class {classname}Service(object):
@staticmethod
def page_list(where, page, per_page):
"""列表记录
Arguments:
where dict -- 查询条件
page int -- 当前页
per_page int -- 每页记录数
return:
Paginate 对象 | None
"""
query = {classname}.Q
if 'id' in where.keys():
query = query.filter({classname}.id == where['id'])
if 'title' in where.keys():
query = query.filter({classname}.title == where['title'])
if 'status' in where.keys():
query = query.filter({classname}.status == where['status'])
else:
query = query.filter({classname}.status != -1)
pagelist_obj = query.paginate(page=page, per_page=per_page)
if pagelist_obj is None:
raise JsonError('暂无数据')
return pagelist_obj
@staticmethod
def get(id):
"""获取单条记录
[description]
Arguments:
id int -- 主键
return:
{classname} Model 实例 | None
"""
if not id:
raise JsonError('ID不能为空')
obj = {classname}.Q.filter({classname}.id == id).first()
return obj
@staticmethod
def update(id, param):
"""更新记录
[description]
Arguments:
id int -- 主键
param dict -- [description]
return:
True | JsonError
"""
columns = [i for (i, _) in {classname}.__table__.columns.items()]
param = {{k:v for k,v in param.items() if k in columns}}
if 'updated_at' in columns:
param['updated_at'] = utime.timestamp(3)
if not id:
raise JsonError('ID 不能为空')
try:
{classname}.Update.filter({classname}.id == id).update(param)
{classname}.session.commit()
return True
except Exception as e:
{classname}.session.rollback()
SysLogger.error(e)
raise JsonError('update error')
@staticmethod
def insert(param):
"""插入
[description]
Arguments:
id int -- 主键
param dict -- [description]
return:
True | JsonError
"""
columns = [i for (i, _) in {classname}.__table__.columns.items()]
param = {{k:v for k,v in param.items() if k in columns}}
if 'created_at' in columns:
param['created_at'] = utime.timestamp(3)
try:
obj = {classname}(**param)
{classname}.session.add(obj)
{classname}.session.commit()
return True
except Exception as e:
{classname}.session.rollback()
SysLogger.error(e)
raise JsonError('insert error')
'''
def render(self, classname, appname = 'admin'):
fname = func.hump2underline(classname)
app = f'{ROOT_PATH}/applications/{appname}'
app_s = f'{app}/services'
sfile = f'{app_s}/{fname}.py'
if os.path.exists(sfile):
return
if not os.path.exists(app):
os.mkdir(app)
if not os.path.exists(app_s):
os.mkdir(app_s)
fout = open(sfile, 'w', encoding='utf8')
output = self.template.format(
classname_underline=fname,
appname=appname,
classname=classname
)
# 写入文件内容
fout.write(output)
# 关闭文件
fout.close()
class AdminHandlerGenerator:
template = '''\
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""{classname}控制器
"""
from trest.router import get
from trest.router import put
from trest.router import post
from trest.router import delete
from trest.exception import JsonError
from applications.admin.utils import required_permissions
from applications.admin.utils import admin_required_login
from applications.admin.services.{classname_underline} import {classname}Service
from .common import CommonHandler
class {classname}Handler(CommonHandler):
@post('{classname_underline}')
@admin_required_login
@required_permissions()
def {classname_underline}_post(self, *args, **kwargs):
param = self.params()
{classname}Service.insert(param)
return self.success()
@get('{classname_underline}/(?P<id>[0-9]+)')
@admin_required_login
@required_permissions()
def {classname_underline}_get(self, id):
"""获取单个记录
"""
resp_data = {classname}Service.get(id)
return self.success(data=resp_data)
@put('{classname_underline}/(?P<id>[0-9]+)')
@admin_required_login
@required_permissions()
def {classname_underline}_put(self, id, *args, **kwargs):
param = self.params()
{classname}Service.update(id, param)
return self.success(data=param)
@delete('{classname_underline}/(?P<id>[0-9]+)')
@admin_required_login
@required_permissions()
def {classname_underline}_delete(self, id, *args, **kwargs):
param = {{
'status':-1
}}
{classname}Service.update(id, param)
return self.success()
class {classname}ListHandler(CommonHandler):
@get(['{classname_underline}','{classname_underline}/(?P<category>[a-zA-Z0-9_]*)'])
@admin_required_login
@required_permissions()
def {classname_underline}_list_get(self, category = '', *args, **kwargs):
"""列表、搜索记录
"""
page = int(self.get_argument('page', 1))
per_page = int(self.get_argument('limit', 10))
id = self.get_argument('id', None)
title = self.get_argument('title', None)
status = self.get_argument('status', None)
param = {{}}
if category:
param['category'] = category
if id:
param['id'] = id
if title:
param['title'] = title
if status:
param['status'] = status
resp_data = {classname}Service.page_list(param, page, per_page)
return self.success(data=resp_data)
'''
def render(self, classname, appname = 'admin'):
fname = func.hump2underline(classname)
outfile = f'{ROOT_PATH}/applications/{appname}/handlers/{fname}.py'
if os.path.exists(outfile):
return
output = self.template.format(
classname_underline=fname,
classname=classname
)
fout = open(outfile, 'w', encoding='utf8')
# 写入文件内容
fout.write(output)
# 关闭文件
fout.close()
class HandlerGenerator:
template = '''\
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""{classname}控制器
"""
import tornado
from trest.router import get
from trest.router import put
from trest.router import post
from trest.router import delete
from trest.exception import JsonError
from applications.{appname}.services.{classname_underline} import {classname}Service
from .common import CommonHandler
class {classname}Handler(CommonHandler):
@post('{classname_underline}')
@tornado.web.authenticated
def {classname_underline}_post(self, *args, **kwargs):
param = self.params()
{classname}Service.insert(param)
return self.success()
@get('{classname_underline}/(?P<id>[0-9]+)')
@tornado.web.authenticated
def {classname_underline}_get(self, id):
"""获取单个记录
"""
resp_data = {classname}Service.get(id)
return self.success(data=resp_data)
@put('{classname_underline}/(?P<id>[0-9]+)')
@tornado.web.authenticated
def {classname_underline}_put(self, id, *args, **kwargs):
param = self.params()
{classname}Service.update(id, param)
return self.success(data=param)
@delete('{classname_underline}/(?P<id>[0-9]+)')
@tornado.web.authenticated
def {classname_underline}_delete(self, id, *args, **kwargs):
param = {{
'status':-1
}}
{classname}Service.update(id, param)
return self.success()
class {classname}ListHandler(CommonHandler):
@get(['{classname_underline}','{classname_underline}/(?P<category>[a-zA-Z0-9_]*)'])
@tornado.web.authenticated
def {classname_underline}_list_get(self, category = '', *args, **kwargs):
"""列表、搜索记录
"""
page = int(self.get_argument('page', 1))
per_page = int(self.get_argument('limit', 10))
id = self.get_argument('id', None)
title = self.get_argument('title', None)
status = self.get_argument('status', None)
param = {{}}
if category:
param['category'] = category
if id:
param['id'] = id
if title:
param['title'] = title
if status:
param['status'] = status
resp_data = {classname}Service.page_list(param, page, per_page)
return self.success(data=resp_data)
'''
def render(self, classname, appname):
fname = func.hump2underline(classname)
app = f'{ROOT_PATH}/applications/{appname}'
app_s = f'{app}/handlers'
sfile = f'{app_s}/{fname}.py'
if os.path.exists(sfile):
return
if not os.path.exists(app):
os.mkdir(app)
if not os.path.exists(app_s):
os.mkdir(app_s)
fout = open(sfile, 'w', encoding='utf8')
output = self.template.format(
classname_underline=fname,
appname=appname,
classname=classname
)
# 写入文件内容
fout.write(output)
# 关闭文件
fout.close()
def get_metadata(tables):
# Use reflection to fill in the metadata
engines = DBConfigParser.parser_engines()
engine = create_engine(engines['default']['master'][0])
metadata = MetaData(engine)
schema = None
noviews = True
# tables = None
metadata.reflect(engine, schema, noviews, tables)
return metadata
def create_models(tables = None):
try:
outfile = f'{ROOT_PATH}/applications/common/models/{tables[0]}.py'
# if os.path.exists(outfile):
# return
metadata = get_metadata(tables)
noindexes = True
noconstraints = True
nojoined = True
noinflect = True
noclasses = False
nocomments = False
# Write the generated model code to the specified file or standard output
generator = ModelGenerator(metadata, noindexes, noconstraints, nojoined, noinflect, noclasses, nocomments=nocomments)
# print('generator ', type(generator), generator)
generator.render(outfile)
except Exception as e:
raise
def create_services(tables, appname = 'admin'):
try:
generator = ServiceGenerator()
for t in tables:
generator.render(func.underline2hump(t, True), appname)
except Exception as e:
raise
def create_handlers(tables, appname = 'admin'):
try:
generator = AdminHandlerGenerator() if appname == 'admin' else HandlerGenerator()
for t in tables:
generator.render(func.underline2hump(t, True), appname)
except Exception as e:
raise
if __name__ == "__main__":
appname = 'ishici'
# 创建命令行解析器句柄,并自定义描述信息
parser = argparse.ArgumentParser(description="test the argparse package")
# 定义可选参数appname
parser.add_argument("--appname", "-a", help="appname must is a string")
# 定义可选参数module
parser.add_argument("--module", "-m", help="multiple modules are separated by commas")
args = parser.parse_args() # 返回一个命名空间
param = vars(args)
appname = param['appname']
modules = []
if appname == 'admin':
metadata = get_metadata(None)
# print(dir(metadata))
for table in metadata.sorted_tables:
create_models([table.name])
create_services([table.name], appname)
create_handlers([table.name], appname)
else:
modules = [m.strip() for m in param['module'].split(',') if m]
create_services(modules, appname)
create_handlers(modules, appname)
try:
[create_models([m]) for m in modules]
except Exception as e:
pass
print(f'create {appname} app, {modules} module success')