Skip to content

Instantly share code, notes, and snippets.

@kosmosr
Created July 18, 2018 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kosmosr/1eaedbffbc5dce41461569384a88140c to your computer and use it in GitHub Desktop.
Save kosmosr/1eaedbffbc5dce41461569384a88140c to your computer and use it in GitHub Desktop.
marshmallow demo
# encoding: utf-8
"""
@author: kosmosr
@contact: zmhwft@gmail.com
@time: 2018/7/17 23:53
"""
from marshmallow import Schema, fields, pre_dump
class Auth:
def __init__(self):
self.base = []
self.seller = []
class BaseAuth:
def __init__(self, bankcard, status=None):
self.status = status
self.bankcard = bankcard
class SellerAuth:
def __init__(self, status, buyer_id):
self.status = status
self.buyer_id = buyer_id
class AuthSchema(Schema):
status = fields.Int(default=1)
bankcard = fields.Str()
class SellerSchema(Schema):
status = fields.Int(default=1)
buyer_id = fields.Int()
class BaseAuthSchema(Schema):
base = fields.Nested(AuthSchema, many=True)
seller = fields.Nested(SellerSchema, many=True)
class Meta:
fields = ('base', 'seller')
@pre_dump
def check_status(self, data):
if data.base[0].status != 3:
self.declared_fields['base'].only = ('status',)
if __name__ == '__main__':
auth = Auth()
auth.base.append(BaseAuth(status=3, bankcard='123'))
auth.seller.append([])
schema = BaseAuthSchema()
result = schema.dump(auth)
print(result.data)
# 默认返回
# check status == 4 返回详细数据
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment