Created
June 20, 2017 17:31
-
-
Save brianv0/d357b95eab66debdf19b53274320a579 to your computer and use it in GitHub Desktop.
Minimal Marshmallow Demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from marshmallow import Schema, fields | |
import json | |
class Database(Schema): | |
class Meta: | |
ordered = True | |
name = fields.String() | |
host = fields.String(attribute="conn_host") | |
port = fields.Integer(attribute="conn_port") | |
default_schema = fields.Function(lambda obj: obj.default_schema.name) | |
if __name__ == '__main__': | |
class Mock(object): | |
pass | |
obj = Mock() | |
default_schema = Mock() | |
default_schema.name = "my_example" | |
data = {"name": "test", | |
"conn_host": "example.com", | |
"conn_port": 80, | |
"default_schema": default_schema | |
} | |
obj.__dict__.update(data) | |
db_schema = Database() | |
print(json.dumps(db_schema.dump(obj).data)) | |
db_schema_basic = Database(only=("name", "host", "port")) | |
print(db_schema_basic.dumps(obj).data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output: