model.tpl 4.59 KB
Newer Older
wanli's avatar
wanli committed
1 2
# -*- coding: utf-8 -*-

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

class {{ config['name'] | letterUpper }}Model(PrimaryModel):
    __tablename__ = '{{ application["tablePrefix"] }}{{ config['name'] }}'
{% for value in config['model']['fields'] %}
{%- if value.get('primaryKey', None) %}
wanli's avatar
wanli committed
13
    {{ value.get('name') }} = db.Column(db.{{ value.get('dataType') }}, primary_key = True)
14
{%- elif value.get('dataType') == "Int" or value.get('dataType') == "Integer" %}
wanli's avatar
wanli committed
15
    {{ 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) %}, default = {{value.get("default")}}{% endif %})
16
{%- else %}
wanli's avatar
wanli committed
17
    {{ 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) %}, default = {{value.get("default")}}{% endif %})
wanli's avatar
wanli committed
18 19
{%- endif %}
{%- endfor %}
wanli's avatar
wanli committed
20 21

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

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

    def __repr__(self):
wanli's avatar
wanli committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
        return '<{{ config['name'] | letterUpper }}Model %r>' % (self.{{ config['model']['fields'][0]["name"] }})

    def to_json(self):
        return {
        {%- for item in config['model']['fields'] %}
        {%- if item.get("toJson") %}
            '{{ item.get("name") }}': self.{{ item.get("name") }},
        {%- endif %}
        {%- endfor %}
        }

{% for key, value in config["view"].items() %}
class {{ key | letterUpper }}{{ config['name'] | letterUpper }}Schema(ma.SQLAlchemySchema):
    class Meta:
        # unknown = INCLUDE # 未知字段默认包含
wanli's avatar
wanli committed
46
        unknown = EXCLUDE # 未知字段默认排除
wanli's avatar
wanli committed
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
        model = {{ config['name'] | letterUpper }}Model
{%- if config['model']['foreignKey'] %}
        include_fk = {{ config['model']['foreignKey'] }}
{% endif %}
{# 
    这里需要判断下,如果是数据库表的字段,则使用auto_field(),否则应该使用json配置中的字段信息 

    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'] %}
72 73 74
{%- 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
75 76 77 78 79 80 81
    {{ 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 %}

{{ key }}{{ config['name'] | letterUpper }}Schema = {{ key | letterUpper }}{{ config['name'] | letterUpper }}Schema()
82
{%- if key == "getList" %}
wanli's avatar
wanli committed
83 84 85
{{ key }}{{ config['name'] | letterUpper }}sSchema = {{ key | letterUpper }}{{ config['name'] | letterUpper }}Schema(many=True)
{%- endif %}
{% endfor %}