model.tpl 4.98 KB
Newer Older
1 2
#!/usr/bin/env python
# -*- coding: utf_8 -*-
wanli's avatar
wanli committed
3

wanli's avatar
wanli committed
4 5 6 7 8 9
from application.app import db, ma
from .base import PrimaryModel
{%- if extend %} {# 判断是否有扩展字段,也就是model对象不包含的字段,因为查询里面还有pagepageSize等这两种字段 #}
from marshmallow import Schema, fields, INCLUDE, EXCLUDE
{%- endif %}

10
class {{ config['name'] | capitalize }}Model(PrimaryModel):
11
    __tablename__ = {% if config.get("model").get("tableName", None) != None %}'{{ config.get("model").get("tableName") }}'{% else %}'{{ application["tablePrefix"] }}{{ config['name'] }}'{% endif %}
wanli's avatar
wanli committed
12 13
{% for value in config['model']['fields'] %}
{%- if value.get('primaryKey', None) %}
wanli's avatar
wanli committed
14
    {{ value.get('name') }} = db.Column(db.{{ value.get('dataType') }}, primary_key = True)
15
{%- elif value.get('dataType') == "Int" or value.get('dataType') == "Integer" %}
16
    {{ value.get('name') }} = db.Column(db.{{ value.get('dataType') }}{% if value.get("length", None) %}{% endif %}{% if value.get("index", False) %}, index = True{% endif %}{% if value.get("required", False) %}, nullable = False{% else %}, nullable = True{% endif %}{% if value.get("default", None) != None %}, default = {{value.get("default")}}{% endif %})
17
{%- else %}
18
    {{ value.get('name') }} = db.Column(db.{{ value.get('dataType') }}{% if value.get("length", None) %}({{value.get("length")}}){% endif %}{% if value.get("index", False) %}, index = True{% endif %}{% if value.get("required", False) %}, nullable = False{% else %}, nullable = True{% endif %}{% if value.get("default", None) != None %}, default = {{value.get("default")}}{% endif %})
wanli's avatar
wanli committed
19 20
{%- endif %}
{%- endfor %}
wanli's avatar
wanli committed
21 22

    # __table_args__ = (
wanli's avatar
wanli committed
23
    #     db.Index('idx_xxx', 'xxx', mysql_using='btree'),
wanli's avatar
wanli committed
24 25
    # )

26
    def __init__(self{% for value in config['model']['fields'] %}, {% if value.get("default", None) != None %}{{ value.get("name") }}={{ value.get("default") }}{% else %}{{ value.get("name") }}{% endif %}{% endfor %}):
wanli's avatar
wanli committed
27
{%- for value in config['model']['fields'] %}
wanli's avatar
wanli committed
28
        self.{{ value.get("name") }} = {{ value.get("name") }}
wanli's avatar
wanli committed
29
{%- endfor %}
wanli's avatar
wanli committed
30 31

    def __repr__(self):
32
        return '<{{ config['name'] | capitalize }}Model %r>' % (self.{{ config['model']['fields'][0]["name"] }})
wanli's avatar
wanli committed
33

34
    def to_dict(self):
wanli's avatar
wanli committed
35 36 37 38 39 40 41 42
        return {
        {%- for item in config['model']['fields'] %}
        {%- if item.get("toJson") %}
            '{{ item.get("name") }}': self.{{ item.get("name") }},
        {%- endif %}
        {%- endfor %}
        }

43 44 45
{%- if "restful" in config.get("view") and config.get("view").get("restful") == False %}
{# do nothing #}
{%- else %}
wanli's avatar
wanli committed
46
{% for key, value in config["view"].items() %}
47
class {{ key | capitalize }}{{ config['name'] | capitalize }}Schema(ma.SQLAlchemySchema):
wanli's avatar
wanli committed
48 49
    class Meta:
        # unknown = INCLUDE # 未知字段默认包含
wanli's avatar
wanli committed
50
        unknown = EXCLUDE # 未知字段默认排除
51
        model = {{ config['name'] | capitalize }}Model
wanli's avatar
wanli committed
52 53 54
{%- if config['model']['foreignKey'] %}
        include_fk = {{ config['model']['foreignKey'] }}
{% endif %}
55 56
{#
    这里需要判断下,如果是数据库表的字段,则使用auto_field(),否则应该使用json配置中的字段信息
wanli's avatar
wanli committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75

    class BandMembersSchema(Schema):
        # missing用来指定反序列化时默认缺省值,default用来指定序列化时默认缺省值
        # 在通常的web api中,dump_onlyload_only参数就类似于“read-only”和“write-only”字段
        id = fields.UUID(missing=uuid.uuid1)
        name = fields.String(required=True, validate=validate.Length(min=1)) # 更多校验类型,移步:https://marshmallow.readthedocs.io/en/stable/api_reference.html#api-validators
        email = fields.Email(data_key="emailAddress") # 解决序列化与反序列化字段不一致问题
        birthdate = fields.DateTime(default=dt.datetime(2017, 9, 29))
        city = fields.String(
            required=True,
            error_messages={"required": {"message": "City required", "code": 400}},
        )
        age = fields.Int(validate=validate.Range(min=18, max=40))
        permission = fields.Str(validate=validate.OneOf(["read", "write", "admin"]))
        password = fields.Str(load_only=True) # password is "write-only"
        created_at = fields.DateTime(dump_only=True) # created_at is "read-only"

#}
{%- for p in value['params'] %}
76 77 78
{%- if p.get("priority") %}
    {{ p.get("name") }} = fields.{{ p.get("dataType") }}(required={{ p.get("required") }}{%- if p.get("dataType") == "String" %}, length={{ p.get("length") }}{%- endif %})
{%- elif p.get("name") in fields %}
wanli's avatar
wanli committed
79 80 81 82 83 84
    {{ p.get("name") }} = ma.auto_field()
{%- else %}
    {{ p.get("name") }} = fields.{{ p.get("dataType") }}(required={{ p.get("required") }}{%- if p.get("dataType") == "String" %}, length={{ p.get("length") }}{%- endif %})
{%- endif %}
{%- endfor %}

85
{{ key }}{{ config['name'] | capitalize }}Schema = {{ key | capitalize }}{{ config['name'] | capitalize }}Schema()
86
{%- if key == "getList" %}
87
{{ key }}{{ config['name'] | capitalize }}sSchema = {{ key | capitalize }}{{ config['name'] | capitalize }}Schema(many=True)
wanli's avatar
wanli committed
88
{%- endif %}
89
{% endfor %}
90
{%- endif %}