mwgencode 1.4.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. gencode/__init__.py +140 -0
  2. gencode/dd_models.py +256 -0
  3. gencode/ext.py +19 -0
  4. gencode/gen_code.py +343 -0
  5. gencode/gencode/__init__.py +0 -0
  6. gencode/gencode/export_class2swgclass.py +206 -0
  7. gencode/gencode/gen_bo_models_code.py +719 -0
  8. gencode/gencode/gen_state_code.py +171 -0
  9. gencode/gencode/gen_swagger_code.py +94 -0
  10. gencode/gencode/gen_tests_code.py +113 -0
  11. gencode/gencode/sample/__init__.py +2 -0
  12. gencode/gencode/sample/babel.cfg +3 -0
  13. gencode/gencode/sample/config-sample.ini +9 -0
  14. gencode/gencode/sample/config.ini +14 -0
  15. gencode/gencode/sample/create_new_table_run.pys +19 -0
  16. gencode/gencode/sample/dockerignore.dock +57 -0
  17. gencode/gencode/sample/file_utils.pys +396 -0
  18. gencode/gencode/sample/gencode.xmi +33 -0
  19. gencode/gencode/sample/gitignore.git +14 -0
  20. gencode/gencode/sample/migrate_run.bat +5 -0
  21. gencode/gencode/sample/migrate_run.pys +9 -0
  22. gencode/gencode/sample/requirements.txt +17 -0
  23. gencode/gencode/sample/run.sh +27 -0
  24. gencode/gencode/sample/seeds/__init__.py +0 -0
  25. gencode/gencode/sample/seeds/models_rm.pys +187 -0
  26. gencode/gencode/sample/seeds/seed_dev_data.pys +21 -0
  27. gencode/gencode/sample/seeds/seed_init.pys +17 -0
  28. gencode/gencode/sample/seeds/seed_rm.pys +39 -0
  29. gencode/gencode/sample/seeds/seed_run.pys +13 -0
  30. gencode/gencode/sample/seeds/seed_utils.pys +23 -0
  31. gencode/gencode/sample/test__init__.pys +6 -0
  32. gencode/gencode/sample/test_run.pys +4 -0
  33. gencode/gencode/sample/utils.pys +92 -0
  34. gencode/gencode/template/Dockerfile.tmp +55 -0
  35. gencode/gencode/template/README.md +91 -0
  36. gencode/gencode/template/__init__.py +0 -0
  37. gencode/gencode/template/__init__.pys +99 -0
  38. gencode/gencode/template/config.pys +134 -0
  39. gencode/gencode/template/default.conf +21 -0
  40. gencode/gencode/template/docker-compose-dev.yaml +52 -0
  41. gencode/gencode/template/docker-compose.yaml +55 -0
  42. gencode/gencode/template/drone.tmp +45 -0
  43. gencode/gencode/template/flask_models.pys +107 -0
  44. gencode/gencode/template/flask_models_base.pys +159 -0
  45. gencode/gencode/template/gen_code_flask.yaml +21 -0
  46. gencode/gencode/template/gen_code_run.pys +28 -0
  47. gencode/gencode/template/k8s-tmp.yml +141 -0
  48. gencode/gencode/template/run.pys +52 -0
  49. gencode/gencode/template/sample.mdj +1193 -0
  50. gencode/gencode/template/setup.tmp +48 -0
  51. gencode/gencode/template/supervisord.conf +21 -0
  52. gencode/gencode/template/swagger_file.yaml +195 -0
  53. gencode/gencode/template/swg_class.tmp +41 -0
  54. gencode/gencode/template/swg_ctrl_code.pys +130 -0
  55. gencode/gencode/template/swg_package_mng.tmp +4423 -0
  56. gencode/gencode/template/test_test_base.tmp +34 -0
  57. gencode/gencode/template/tests/__init__.py +0 -0
  58. gencode/gencode/template/tests/__init__.pys +5 -0
  59. gencode/gencode/template/tests/init_test_data.pys +80 -0
  60. gencode/gencode/template/tests/run.pys +4 -0
  61. gencode/gencode/template/tests/test_base.pys +87 -0
  62. gencode/gencode/template/tests/test_classmng.pys +58 -0
  63. gencode/gencode/template/uwsgi.ini +20 -0
  64. gencode/gencode/template/uwsgi_run.pys +44 -0
  65. gencode/importmdj/__init__.py +0 -0
  66. gencode/importmdj/import_dd_classes.py +369 -0
  67. gencode/importmdj/import_swagger2_class.py +371 -0
  68. gencode/importmdj/import_uml_models.py +466 -0
  69. gencode/importxmi/__init__.py +1 -0
  70. gencode/importxmi/import_classes.py +342 -0
  71. gencode/importxmi/import_sequences.py +291 -0
  72. gencode/importxmi/import_states.py +150 -0
  73. gencode/importxmi/import_swagger.py +151 -0
  74. gencode/swg2_class_models.py +179 -0
  75. gencode/uml_class_models.py +295 -0
  76. gencode/upgrade.py +113 -0
  77. gencode/utils.py +225 -0
  78. manage.py +194 -0
  79. mwgencode-1.4.1.dist-info/METADATA +325 -0
  80. mwgencode-1.4.1.dist-info/RECORD +84 -0
  81. mwgencode-1.4.1.dist-info/WHEEL +5 -0
  82. mwgencode-1.4.1.dist-info/entry_points.txt +2 -0
  83. mwgencode-1.4.1.dist-info/licenses/LICENSE.txt +19 -0
  84. mwgencode-1.4.1.dist-info/top_level.txt +2 -0
@@ -0,0 +1,134 @@
1
+ import os
2
+ from mwutils.mw_consul import DatabaseConf,RedisConf,ServiceConf{% if 'kafka' in plugins %}, KafkaConf{% endif %}
3
+ basedir = os.path.abspath(os.path.dirname(__file__))
4
+ # conf_parse = getConfig(__file__)
5
+
6
+ #################################################################
7
+ # 在config.ini中app_config.config=development 时为开发者模式,
8
+ # 开发者模式使用DevelopmentConfig,所有配置在DevelopmentConfig中手动设定
9
+ # 开发者模式只需要开启dev 模式的consul(命令:consul agent dev)即可
10
+ # 不需要kong认证,认证信息在DevelopmentConfig设定
11
+ # 注意:开发者模式不允许在生产环境中使用,否则会引起安全性问题
12
+ ###################################################################
13
+ is_development =os.environ.get('IS_DEVELOPMENT', 'false').lower()=='true'
14
+ # value:0 :普通;1:哨兵;2:集群
15
+ redis_model = int(ServiceConf.get_keyvalue('redis_model','0')) if not is_development else int(os.environ.get('REDIS_MODEL', '0'))
16
+ # 0:普通,1:双机备份
17
+ database_model = int(ServiceConf.get_keyvalue('database_model','0')) if not is_development else int(os.environ.get('DATABASE_MODEL', '0'))
18
+
19
+ class Config:
20
+ URL_PREFIX_SCH = ''
21
+ DEBUG = False
22
+ DEVELOPMENT = False
23
+ TESTING = False
24
+ PORT = 8080
25
+ {% if include_model %}
26
+ SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess maxwin password'
27
+ SQLALCHEMY_COMMIT_ON_TEARDOWN = True
28
+ {% endif %}
29
+ @staticmethod
30
+ def init_app(app):
31
+ pass
32
+
33
+
34
+ @classmethod
35
+ def get_host_addr(cls):
36
+ from mwsdk import AgentConf
37
+ # 支持k8s
38
+ if os.environ.get('SUPPORT_K8S', 'false').lower() == 'true' :
39
+ return 'auth-server'
40
+ return AgentConf().bind_ip
41
+
42
+ class TestingConfig(Config):
43
+ PORT = 9999
44
+ DEBUG = True
45
+ TESTING = True
46
+ LOG_LEVEL = 10
47
+ # True 开发模式,会跳过权限检查
48
+ DEVELOPMENT = False
49
+ # True自动注册到kong,False不做
50
+ KONG_AUTO_REGISTER = False
51
+ # True自动注册到consul,False不做
52
+ CONSUL_AUTO_REGISTER = False
53
+ REDIS_URL = 'redis://192.168.101.70:6380/0'
54
+ {% if include_model %}
55
+ # 开发模式下的登录用户
56
+ LOGIN_USER_NAME = 'dev'
57
+ # 开发模式下的用户ID
58
+ LOGIN_USER_ID = '2000'
59
+ SYSTEM_NAME = 'test'
60
+ # 输出sql
61
+ SQLALCHEMY_ECHO = False
62
+ SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
63
+ {% endif %}
64
+ class DevelopmentConfig(Config):
65
+ DEBUG = True
66
+ PORT = 8888
67
+ # 输出log为debug
68
+ LOG_LEVEL = 10
69
+ # True 开发模式,会跳过权限检查
70
+ DEVELOPMENT = True
71
+ # True自动注册到kong,False不做
72
+ KONG_AUTO_REGISTER = False
73
+ # True自动注册到consul,False不做
74
+ CONSUL_AUTO_REGISTER = False
75
+ {% if include_model %}
76
+ # 开发模式下的登录用户
77
+ LOGIN_USER_NAME = os.environ.get('LOGIN_USER_NAME','dev')
78
+ # 开发模式下的用户ID
79
+ LOGIN_USER_ID = os.environ.get('LOGIN_USER_ID','2222')
80
+ LOGIN_USER_SYSTEMUSER=True
81
+ # LOGIN_USER_MANAGEUSER=False
82
+ # LOGIN_USER_MANAGEUSER_ID=''
83
+ # 指定用户关联的公司,方便调试
84
+ LOGIN_USER_COMPANYID = os.environ.get('LOGIN_USER_COMPANYID','string')
85
+ SYSTEM_NAME = os.environ.get('SYSTEM_NAME','maxguide')
86
+ SYSTEM_ID = os.environ.get('SYSTEM_ID','mis0')
87
+ # 输出sql
88
+ SQLALCHEMY_ECHO = True
89
+ # SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
90
+ # SQLALCHEMY_DATABASE_URI = os.environ.get('sql','sqlite:///' + os.path.join(basedir, 'data-dev.sqlite'))
91
+ SQLALCHEMY_DATABASE_URI = os.environ.get('sql',"mssql+pymssql://sa:111@192.168.101.238:1433/gxtest")
92
+ # SQLALCHEMY_DATABASE_URI = "mysql+mysqldb://root:111@192.168.101.33:3306/ms"
93
+ {% endif %}
94
+ UPLOAD_FOLDER = 'E://files'
95
+ # value:0 :普通;1:哨兵;2:集群
96
+ REDIS_MODEL = 0
97
+ REDIS_URL = 'redis+sentinel://192.168.101.72:26390,192.168.101.73:26390,192.168.101.74:26390,192.168.101.81:26390,192.168.101.80:26390/mymaster/0' \
98
+ if redis_model==1 else\
99
+ os.environ.get('redis','redis://192.168.101.70:6380/0')
100
+ {% if 'kafka' in plugins %}
101
+ KAFKA_CONFIG = {'bootstrap.servers': '192.168.101.72,192.168.101.73,192.168.101.74'}
102
+ {% endif %}
103
+ SESSION_EXPIRATION_TIME = 0
104
+
105
+ class ProductionConfig(Config):
106
+ PORT = int(os.environ.get('WEB_PORT',8081))
107
+ {% if include_model %}
108
+ # 权限用的系统名
109
+ SYSTEM_NAME = os.environ.get('SYSTEM_NAME','maxguide')
110
+ SQLALCHEMY_ECHO = os.environ.get('SQLALCHEMY_ECHO','false').lower()=='true'
111
+ SQLALCHEMY_DATABASE_URI = DatabaseConf(os.environ.get('DATABASE_NAME','maxbus')).\
112
+ sqlalchemy_database_uri() if not is_development else ''
113
+ {% endif %}
114
+ REDIS_URL =RedisConf('session',model=redis_model).redis_url() if not is_development else ''
115
+ LOG_LEVEL = int(os.environ.get('LOG_LEVEL',20))
116
+ # True自动注册到kong,False不做
117
+ KONG_AUTO_REGISTER = os.environ.get('KONG_AUTO_REGISTER','true').lower()=='true'
118
+ # True自动注册到consul,False不做
119
+ CONSUL_AUTO_REGISTER = os.environ.get('CONSUL_AUTO_REGISTER','false').lower()=='true'
120
+ {% if 'kafka' in plugins %}
121
+ KAFKA_CONFIG = {'bootstrap.servers': KafkaConf().bootstrap_servers} if not is_development else {}
122
+ {% endif %}
123
+ UPLOAD_FOLDER = os.environ.get('UPLOAD_FOLDER', os.getcwd())
124
+ SESSION_EXPIRATION_TIME = int(os.environ.get('SESSION_EXPIRATION_TIME',0))
125
+ config = {
126
+ 'development': DevelopmentConfig,
127
+ 'testing': TestingConfig,
128
+ 'production': ProductionConfig,
129
+ 'default': ProductionConfig if not is_development else DevelopmentConfig
130
+ }
131
+ if __name__ == '__main__':
132
+ conf = config['default']
133
+ print(conf.PORT)
134
+ print(config['default'].PORT)
@@ -0,0 +1,21 @@
1
+
2
+ # 上传文件的最大size
3
+ client_max_body_size 250M;
4
+
5
+ upstream flask {
6
+ # server unix:///path/to/your/mysite/mysite.sock; # for a file socket
7
+ server unix:///tmp/uwsgi.sock;
8
+ #server 127.0.0.1:5000; # for a web port socket (we'll use this first)
9
+ }
10
+ server {
11
+ listen {{port}};
12
+ #server_name localhost;
13
+
14
+ #charset koi8-r;
15
+ #access_log /var/log/nginx/host.access.log main;
16
+ location / {
17
+ include uwsgi_params;
18
+ uwsgi_pass flask;
19
+ }
20
+
21
+ }
@@ -0,0 +1,52 @@
1
+ version: '2'
2
+ services:
3
+ {{ swagger.name }}:
4
+ build: .
5
+ # image名稱,被docker registrator作為服務名註冊
6
+ image: {{swagger.name}}:1.0.0
7
+ container_name: {{swagger.name}}_python3.7
8
+ restart: always
9
+ network_mode: bridge
10
+ environment:
11
+ # python程序通過這個變量找到consul
12
+ CONSUL_HTTP_ADDR: ${CONSUL_HTTP_ADDR} #192.168.101.88:8500
13
+ WEB_PORT : ${WEB_PORT} #8001
14
+ DATABASE_NAME : ${DATABASE_NAME} #maxbus
15
+ # 系统权限名称
16
+ SYSTEM_NAME : ${SYSTEM_NAME}
17
+ # 第一層權限的ID
18
+ SYSTEM_ID : ${SYSTEM_ID}
19
+ # true自動註冊到kong,false 不會註冊
20
+ # 注意:值為true時,需要ports中設定的內外IP設為相等
21
+ KONG_AUTO_REGISTER: ${KONG_AUTO_REGISTER}
22
+ CONSUL_AUTO_REGISTER: ${CONSUL_AUTO_REGISTER}
23
+ LOG_LEVEL: ${LOG_LEVEL}
24
+ UPLOAD_FOLDER: ${UPLOAD_FOLDER}
25
+ SWAGGER_HOST: ${SWAGGER_HOST}
26
+ SESSION_EXPIRATION_TIME: ${SESSION_EXPIRATION_TIME}
27
+ SERVICE_IGNORE: 'true'
28
+ ports:
29
+ - ${WEB_PORT}:80
30
+ {% if 'kafka' in plugins %}
31
+ extra_hosts:
32
+ - de9-72:192.168.101.72
33
+ - de9-73:192.168.101.73
34
+ - de9-74:192.168.101.74
35
+ {% endif %}
36
+ volumes:
37
+ - /usr/share/zoneinfo/Asia/Taipei:/usr/share/zoneinfo/Asia/Taipei
38
+ - /usr/share/zoneinfo/Asia/Taipei:/etc/localtime/
39
+ - /etc/timezone:/etc/timezone
40
+ # 调试代码时,不用每次都重建镜像
41
+ #- .:/var/{{swagger.name}}
42
+ # 支持ngix + uwsgi
43
+ - ./supervisord.conf:/etc/supervisor.d/supervisord.conf
44
+ - ./default.conf:/etc/nginx/conf.d/default.conf
45
+ - ./uwsgi.ini:/var/{{swagger.name}}/uwsgi.ini
46
+ working_dir: /var/{{swagger.name}}
47
+ # command: ["python3","run.py"]
48
+ logging:
49
+ driver: "json-file"
50
+ options:
51
+ max-size: "50m"
52
+ max-file: "10"
@@ -0,0 +1,55 @@
1
+ version: '2'
2
+ services:
3
+ {{ swagger.name }}:
4
+ # image: cxhjet/flask-py3.6:1.8
5
+ # build: .
6
+ build:
7
+ context: .
8
+ dockerfile: Dockerfile_dev
9
+ # image名稱,被docker registrator作為服務名註冊
10
+ image: {{swagger.name}}:1.0.0
11
+ container_name: {{swagger.name}}_python3.6
12
+ restart: always
13
+ network_mode: bridge
14
+ environment:
15
+ # python程序通過這個變量找到consul
16
+ CONSUL_HTTP_ADDR: ${CONSUL_HTTP_ADDR} #192.168.101.88:8500
17
+ WEB_PORT : ${WEB_PORT} #8001
18
+ DATABASE_NAME : ${DATABASE_NAME} #maxbus
19
+ # 系统权限名称
20
+ SYSTEM_NAME : ${SYSTEM_NAME}
21
+ # true自動註冊到kong,false 不會註冊
22
+ # 注意:值為true時,需要ports中設定的內外IP設為相等
23
+ KONG_AUTO_REGISTER: ${KONG_AUTO_REGISTER}
24
+ CONSUL_AUTO_REGISTER: ${CONSUL_AUTO_REGISTER}
25
+ LOG_LEVEL: ${LOG_LEVEL}
26
+ SESSION_EXPIRATION_TIME: ${SESSION_EXPIRATION_TIME}
27
+ SERVICE_IGNORE: 'true'
28
+ ports:
29
+ - ${WEB_PORT}:80
30
+ {% if 'kafka' in plugins %}
31
+ extra_hosts:
32
+ - de9-72:192.168.101.72
33
+ - de9-73:192.168.101.73
34
+ - de9-74:192.168.101.74
35
+ {% endif %}
36
+ volumes:
37
+ # - /usr/share/zoneinfo/Asia/Taipei:/usr/share/zoneinfo/Asia/Taipei
38
+ # - /usr/share/zoneinfo/Asia/Taipei:/etc/localtime/
39
+ # - /etc/timezone:/etc/timezone
40
+ - /F/docker_store/app-config/zoneinfo/Asia/Taipei:/usr/share/zoneinfo/Asia/Taipei
41
+ - /F/docker_store/app-config/zoneinfo/Asia/Taipei:/etc/localtime/
42
+ - /F/docker_store/app-config/zoneinfo/timezone:/etc/timezone
43
+ # 不用每次都重建镜像
44
+ #- .:/var/{{swagger.name}}
45
+ # 支持ngix + uwsgi
46
+ - ./supervisord.conf:/etc/supervisor.d/supervisord.conf
47
+ - ./default.conf:/etc/nginx/conf.d/default.conf
48
+ - ./uwsgi.ini:/var/{{swagger.name}}/uwsgi.ini
49
+ working_dir: /var/{{swagger.name}}
50
+ # command: ["python3","run.py"]
51
+ logging:
52
+ driver: "json-file"
53
+ options:
54
+ max-size: "50m"
55
+ max-file: "10"
@@ -0,0 +1,45 @@
1
+ kind: pipeline
2
+ type: docker
3
+ name: {{swagger.name}}
4
+ steps:
5
+
6
+ # - name: push-image
7
+ # image: plugins/docker
8
+ # settings:
9
+ # dockerfile: Dockerfile
10
+ # repo: maxwinch/{{swagger.name}}
11
+ # use_cache: true
12
+ # username:
13
+ # from_secret: DOCKER_USER
14
+ # password:
15
+ # from_secret: DOCKER_PASSWORD
16
+ # tags:
17
+ # - latest
18
+ # when:
19
+ # event: push
20
+ # branch: master
21
+
22
+ - name: push_maxwin_latest
23
+ image: plugins/docker
24
+ settings:
25
+ insecure: true
26
+ dockerfile: Dockerfile
27
+ repo: cicd-so-happy.maxwin.com.tw:5000/{{swagger.name}}
28
+ registry: cicd-so-happy.maxwin.com.tw:5000
29
+ tags:
30
+ - latest
31
+ when:
32
+ branch: master
33
+
34
+ - name: push_maxwin_tag
35
+ image: plugins/docker
36
+ settings:
37
+ dockerfile: Dockerfile
38
+ repo: cicd-so-happy.maxwin.com.tw:5000/{{swagger.name}}
39
+ registry: cicd-so-happy.maxwin.com.tw:5000
40
+ use_cache: true
41
+ tags: ${DRONE_TAG}
42
+ insecure: true
43
+ when:
44
+ event:
45
+ - tag
@@ -0,0 +1,107 @@
1
+ from sqlalchemy import Table,Column, Integer, String, ForeignKey, Boolean,\
2
+ DateTime,Time,Date,Float
3
+ from sqlalchemy.orm import relationship,aliased
4
+ from sqlalchemy import or_
5
+ from .ext import Base as Model
6
+ import json
7
+ from enum import Enum
8
+
9
+ class SqlType(Enum):
10
+ mysql = 0 #'mysql+mysqldb'
11
+ mssql = 1 #'mssql+pymssql'
12
+ sqlite = 2 #'sqlite:'
13
+ def getSqlType():
14
+ sql_uri = current_app.config['SQLALCHEMY_DATABASE_URI']
15
+ if sql_uri.startswith('mysql+mysqldb'):
16
+ return SqlType.mysql.value
17
+ elif sql_uri.startswith('mssql+pymssql'):
18
+ return SqlType.mssql.value
19
+ elif sql_uri.startswith('sqlite:'):
20
+ return SqlType.sqlite.value
21
+ else:
22
+ assert False,'不能识别的SQL驱动,%s'%sql_uri
23
+ def new_id():
24
+ if getSqlType() == SqlType.sqlite.value:
25
+ import uuid
26
+ return str(uuid.uuid1())
27
+ else:
28
+ connection = db.engine.raw_connection()
29
+ try:
30
+ cursor = connection.cursor()
31
+ if getSqlType()==SqlType.mysql.value:
32
+ cursor.callproc("sp_getobjectids_new", [1])
33
+ elif getSqlType()==SqlType.mssql.value:
34
+ # 不知为何cursor.callproc 在 mssql中取不到资料??
35
+ cursor.execute("exec pro_gettableid 1")
36
+ newid = cursor.fetchone()[0]
37
+ cursor.close()
38
+ connection.commit()
39
+ finally:
40
+ connection.close()
41
+ return str(newid)
42
+
43
+ {% for enum in enumerations %}
44
+ class {{enum.name}}(Enum):
45
+ {% for k,v in enum.columns.items() %}
46
+ {{k}} ={{v}}
47
+ {% endfor %}
48
+ {% endfor %}
49
+
50
+ {% for _,table in metatables.items() %}
51
+ {{ table.class_name }} = Table('{{table.table_name}}', Model.metadata,
52
+ Column('{{table['columns'][0].dbname}}',{{table['columns'][0].type}}, ForeignKey('{{table['columns'][0].reftable}}.{{table['columns'][0].refid}}')),
53
+ Column('{{table['columns'][1].dbname}}',{{table['columns'][1].type}}, ForeignKey('{{table['columns'][1].reftable}}.{{table['columns'][1].refid}}'))
54
+ )
55
+ {% endfor %}
56
+
57
+
58
+ {% for _,table in tables.items() %}
59
+ class {{ table.class_name }}({% if table.parent_name %}{{table.parent_name}}{% else %}Model{% endif %}):
60
+ {% if table.doc %}
61
+ """
62
+ {{table.doc}}
63
+ """
64
+ {% endif %}
65
+ {% if table.table_name %}
66
+ __tablename__ = '{{table.table_name}}'
67
+ {% endif %}
68
+ {% if table.discriminator_column %}
69
+ {{table.discriminator_column.name}} = Column({{table.discriminator_column.dbname}}{{table.discriminator_column.type}})
70
+ {% endif %}
71
+ {% if table.mapper_args %}
72
+ __mapper_args__ = {{table.mapper_args}}
73
+ {% endif %}
74
+ {% for uc in table.unique_constraints %}
75
+ {{ uc }}
76
+ {% endfor %}
77
+ {% for fld in table.columns %}
78
+ {% if fld.doc %}
79
+ # {{fld.doc}}
80
+ {% endif %}
81
+ {{fld.name}} = Column({{fld.dbname}}{{fld.type}}{{fld.default}}{{fld.unique}}{{fld.nullable}}{{fld.primary_key}})
82
+ {% endfor %}
83
+ {% for fld in table.fkeyids %}
84
+ {{fld.name}} = Column({{fld.dbname}}{{fld.type}},ForeignKey("{{fld.reftable}}.{{fld.refid}}"){{fld.default}}{{fld.unique}}{{fld.nullable}}{{fld.primary_key}})
85
+ {% endfor %}
86
+ {% for rs in table.relationsips %}
87
+ {{rs.name}} = relationship("{{rs.relationship_cls}}"{{rs.back_populates}}{{rs.uselist}}{{rs.foreign_keys}}{{rs.secondary}}{{rs.lazy}}{{rs.cascade}}{{rs.remote_side}}{{rs.primaryjoin}}{{rs.order_by}})
88
+ {% endfor %}
89
+
90
+ {% for func in table.funcs %}
91
+ {%if func.isstatic%}
92
+ @staticmethod
93
+ {% endif %}
94
+ def {{func.name}}({{func.self_param}}{{func.params}}):
95
+ {{func.codes}}
96
+ {% endfor %}
97
+
98
+
99
+ def __repr__(self):
100
+ return json.dumps(self.to_json())
101
+
102
+ def to_json(self):
103
+ return {key: getattr(self, key) for key in self.__table__.columns.keys()
104
+ if hasattr(self,key)
105
+ }
106
+
107
+ {% endfor %}
@@ -0,0 +1,159 @@
1
+ """
2
+ NOTE: This unit is auto generated by the gencode.
3
+ Do not edit these code manually.
4
+ """
5
+ from app import db
6
+ from datetime import datetime,timedelta,date
7
+ import json
8
+ from enum import Enum
9
+ from flask import current_app
10
+ import decimal
11
+ from mwutils.mw_time import date2str,datetime2isostr,get_locale_timezone
12
+
13
+ class DecimalEncoder(json.JSONEncoder):
14
+ def default(self, o):
15
+ if isinstance(o, decimal.Decimal):
16
+ return float(o)
17
+ elif isinstance(o,datetime):
18
+ return date2str(o)
19
+ elif isinstance(o, timedelta):
20
+ return str(o)
21
+ elif isinstance(o,datetime):
22
+ if o.tzinfo is None:
23
+ return datetime2isostr(o.astimezone(get_locale_timezone()))
24
+ return datetime2isostr(o)
25
+ super(DecimalEncoder, self).default(o)
26
+
27
+ class SqlType(Enum):
28
+ mysql = 0 #'mysql+mysqldb'
29
+ mssql = 1 #'mssql+pymssql'
30
+ sqlite = 2 #'sqlite:'
31
+
32
+ def getSqlType():
33
+ sql_uri = current_app.config['SQLALCHEMY_DATABASE_URI']
34
+ if sql_uri.startswith('mysql+mysqldb'):
35
+ return SqlType.mysql.value
36
+ elif sql_uri.startswith('mssql+pymssql'):
37
+ return SqlType.mssql.value
38
+ elif sql_uri.startswith('sqlite:'):
39
+ return SqlType.sqlite.value
40
+ else:
41
+ assert False,'不能识别的SQL驱动,%s'%sql_uri
42
+
43
+ def new_id():
44
+ if getSqlType() == SqlType.sqlite.value:
45
+ import uuid
46
+ return str(uuid.uuid1())
47
+ else:
48
+ connection = db.engine.raw_connection()
49
+ try:
50
+ cursor = connection.cursor()
51
+ if getSqlType()==SqlType.mysql.value:
52
+ cursor.callproc("sp_getobjectids_new", [1])
53
+ elif getSqlType()==SqlType.mssql.value:
54
+ # 不知为何cursor.callproc 在 mssql中取不到资料??
55
+ cursor.execute("exec pro_gettableid 1")
56
+ newid = cursor.fetchone()[0]
57
+ cursor.close()
58
+ connection.commit()
59
+ finally:
60
+ connection.close()
61
+ return str(newid)
62
+
63
+ def get_companyids(company_id):
64
+ '''
65
+ 获取公司下包括自身的所有公司的id
66
+ '''
67
+ if not company_id:
68
+ return []
69
+ connection = db.engine.raw_connection()
70
+ result = []
71
+ try:
72
+ cursor = connection.cursor()
73
+ if getSqlType()==SqlType.mysql.value:
74
+ cursor.callproc("pro_getcompanys", [company_id])
75
+ else:
76
+ cursor.execute("exec pro_getcompanys %s"%company_id)
77
+ for data in cursor.fetchall():
78
+ result.append(data[0])
79
+ cursor.close()
80
+ finally:
81
+ connection.close()
82
+ return result
83
+
84
+ {% for enum in enumerations %}
85
+ class {{enum.name}}(Enum):
86
+ {% for k,v in enum.columns.items() %}
87
+ {{k}} ={{v}}
88
+ {% endfor %}
89
+ {% endfor %}
90
+
91
+ {% for _,table in metatables.items() %}
92
+ {{ table.class_name }} = db.Table('{{table.table_name}}', db.Model.metadata,
93
+ db.Column('{{table['columns'][0].dbname}}',{{table['columns'][0].type}}, db.ForeignKey('{{table['columns'][0].reftable}}.{{table['columns'][0].refid}}')),
94
+ db.Column('{{table['columns'][1].dbname}}',{{table['columns'][1].type}}, db.ForeignKey('{{table['columns'][1].reftable}}.{{table['columns'][1].refid}}'))
95
+ )
96
+ {% endfor %}
97
+
98
+
99
+ {% for _,table in tables.items() %}
100
+ class {{ table.class_name }}{% if not table.is_sigletable %}_base{% endif %}({% if table.parent_name %}{{table.parent_name}}{% else %}db.Model{% endif %}):
101
+ {% if table.doc %}
102
+ """
103
+ {{table.doc}}
104
+ """
105
+ {% endif %}
106
+ {% if table.table_name %}
107
+ __tablename__ = '{{table.table_name}}'
108
+ {% endif %}
109
+ {% if table.discriminator_column %}
110
+ {{table.discriminator_column.name}} = db.Column({{table.discriminator_column.dbname}}{{table.discriminator_column.type}})
111
+ {% endif %}
112
+ {% if table.mapper_args %}
113
+ __mapper_args__ = {{table.mapper_args}}
114
+ {% endif %}
115
+ {% if table.table_args %}
116
+ __table_args__ = {{table.table_args}}
117
+ {% endif %}
118
+ {% if table.bind_key %}
119
+ __bind_key__ = '{{table.bind_key}}' # 已设置__bind_key__ 数据库名
120
+ {% endif %}
121
+ {% for uc in table.unique_constraints %}
122
+ {{ uc }}
123
+ {% endfor %}
124
+ {% for fld in table.columns %}
125
+ {% if fld.doc %}
126
+ # {{fld.doc}}
127
+ {% endif %}
128
+ {{fld.name}} = db.Column({{fld.dbname}}{{fld.type}}{{fld.default}}{{fld.unique}}{{fld.nullable}}{{fld.primary_key}}, comment="{{(fld.doc or "").replace("'","\'").replace('"','\\"')}}")
129
+ {% endfor %}
130
+ {% for fld in table.fkeyids %}
131
+ {{fld.name}} = db.Column({{fld.dbname}}{{fld.type}},db.ForeignKey("{{fld.reftable}}.{{fld.refid}}"{{fld.ondelete}}){{fld.default}}{{fld.unique}}{{fld.nullable}}{{fld.primary_key}})
132
+ {% endfor %}
133
+ {% for rs in table.relationsips %}
134
+ {{rs.name}} = db.relationship("{{rs.relationship_cls}}"{{rs.back_populates}}{{rs.uselist}}{{rs.foreign_keys}}{{rs.secondary}}{{rs.lazy}}{{rs.cascade}}{{rs.remote_side}}{{rs.primaryjoin}}{{rs.order_by}})
135
+ {% endfor %}
136
+
137
+ {% for func in table.funcs %}
138
+ {%if func.isstatic%}
139
+ @staticmethod
140
+ {% endif %}
141
+ def {{func.name}}({{func.self_param}}{{func.params}}):
142
+ {{func.codes}}
143
+ {% endfor %}
144
+
145
+
146
+ def __repr__(self):
147
+ return json.dumps(self.to_json(),cls = DecimalEncoder)
148
+
149
+ def to_json(self,fields:list=None):
150
+ '''
151
+ 按资料库中的fieldname输出json
152
+ :param fields:资料库栏位名,不指定fields时,输出所有的资料,否则按指定fields输出
153
+ :return:
154
+ '''
155
+ return {key: getattr(self, key) for key in (fields or self.__table__.columns.keys())
156
+ if hasattr(self,key)
157
+ }
158
+
159
+ {% endfor %}
@@ -0,0 +1,21 @@
1
+ version: '2'
2
+ project:
3
+ type: {{pro_type}}
4
+ rootpath: .
5
+ doc_dir: docs
6
+ units:
7
+ swagger: true,
8
+ model: true,
9
+ test: false,
10
+ seeds: false,
11
+ services:
12
+ - redis
13
+ # - kafka
14
+ # - mongodb
15
+ models:
16
+ main:
17
+ name: {{pro_name}}
18
+ file: {{pro_name}}.mdj
19
+
20
+
21
+
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env python
2
+
3
+ from gencode.gen_code import GenCode,GenProject_Flask,GenSwagger
4
+
5
+ if __name__ == '__main__':
6
+ rootpath = r'.'
7
+ umlfile = r'./docs/{{pro_name}}.mdj'
8
+ g = GenCode(umlfile,rootpath)
9
+ # 把boclass 汇出成 swagger class
10
+ g.export(umlfile,umlfile,exclude_classes=['employee','depart','company','company_auth'])
11
+
12
+ # 从modelfile中汇入到swagerfile中,并生成swagger类,不会重复导入
13
+ # swg = GenSwagger(umlfile,rootpath)
14
+ # swg.export_one_swgclass('MemberUser',xmifile)
15
+ # # 为swagger类增加 方法,范例
16
+ # swg.add_operation('EmpUsermng', 'empuser_register', 'post')
17
+ # swg.add_operation('verificationcode_mng', 'email_verificationcode', 'get')
18
+
19
+ # 产生model单元,type= flask:产生flask_sqlalchemy 的 model
20
+ # type = sql :产生 sqlalchemy 的 model
21
+ g.model()
22
+ p = GenProject_Flask(umlfile, rootpath)
23
+ # 产生专案代码
24
+ p.gen_code()
25
+
26
+
27
+
28
+