Last active
August 29, 2015 14:27
-
-
Save iiogmgo/45ed5e9c1ad35a7a2ab5 to your computer and use it in GitHub Desktop.
just study
This file contains 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, ValidationError, pprint | |
from collections import OrderedDict | |
# model | |
import datetime as dt | |
class User(object): | |
def __init__(self, email, provider): | |
self.email = email | |
self.provider = provider | |
self.created_at = dt.datetime.now() | |
def __repr__(self): | |
return '<User(provider={self.provider!r})>'.format(self=self) | |
# Custom validator | |
def must_not_be_blank(data): | |
if not data: | |
raise ValidationError('Data not provided.') | |
def validate_provider(provider): | |
provider_list = ['facebook', 'naver', 'google'] | |
if provider not in provider_list: | |
raise ValidationError('Provider must be in provider_list') | |
# schema | |
class UserSchema(Schema): | |
email_address = fields.Email( | |
attribute="email", # column name from model data, it's for serialize | |
load_from="email_data" # column name from load data, it's for de_serialize | |
) | |
provider = fields.String( | |
validate=validate_provider, # custom validation | |
required='provider is required!', # set required message | |
load_only=True # write-only | |
) | |
created_at = fields.DateTime( | |
dump_only=True # read-only | |
) | |
class Meta: | |
ordered = True | |
def make_object(self, data): | |
return User(**data) | |
class TestSchema(Schema): | |
upper = fields.Function(lambda obj:obj.provider.upper()) | |
class Meta: | |
fields = ["email", "provider", "upper"] | |
ordered = True | |
# test def - serialize (use dump) | |
# object -> json_data | |
def serializing_test(): | |
user = User(email='123@nate.com', provider='facebook') | |
schema = UserSchema() | |
result = schema.dump(user) | |
print("====== object -> json_data ======"+"\n") | |
print(user) | |
print("\n"+" dump") | |
print(" ▼"+"\n") | |
pprint(result.data, indent=2) | |
def serializing_many(): | |
user1 = User(email='123@nate.com', provider='facebook') | |
user2 = User(email='hello@gmail.com', provider='google') | |
user = [user1, user2] | |
schema = UserSchema(many=True) # OR UserSchema().dump(user, many=True) | |
# if you don't use many option, | |
# "TypeError: list indices must be integers, not str" | |
result = schema.dump(user) | |
pprint(result.data) | |
# test def - deserialize (use load) | |
# json_data -> object | |
def de_serializing_test(): | |
user = { | |
'email_data': 'asdf@nate.com', | |
'provider': 'naver' | |
} | |
schema = UserSchema() | |
result = schema.load(user) | |
user_object = result.data | |
print("====== json_data -> object ====== ") | |
print(""" | |
{ | |
'email_data': 'asdf@nate.com', | |
'provider': 'naver' | |
} | |
""") | |
print(" load") | |
print(" ▼"+"\n") | |
pprint(user_object, indent=2) | |
# test main | |
if __name__ == "__main__": | |
de_serializing_test() # load | |
print("\n") | |
serializing_test() # dump | |
# validation and custom validation | |
# strict mode | |
print("\n"+"====== check validation ======"+"\n") | |
user1 = {'email_data': 'mick@gmail.com', 'provider': 'facebook'} | |
print(user1) | |
try: | |
result = UserSchema(strict=True).load(user1) | |
except ValidationError as err: | |
print(err) | |
else: | |
print("pass and load!") | |
pprint(result.data) | |
print("\n"+"====== check validation ======"+"\n") | |
user2 = {'email_data': 'mick', 'provider': 'fbook'} | |
print(user2) | |
try: | |
result = UserSchema(strict=True).load(user2) | |
except ValidationError as err: | |
print("error!") | |
print(err) | |
else: | |
pprint(result.data.email) | |
""" | |
# Ordering Output and Implicit Field | |
u = User('charlie@stones.com', 'facebook') | |
schema = TestSchema() | |
result = schema.dump(u) | |
assert isinstance(result.data, OrderedDict) | |
pprint(result.data, indent=2) | |
""" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment