Skip to content

Instantly share code, notes, and snippets.

@allenyang79
Last active November 2, 2017 02:20
Show Gist options
  • Save allenyang79/e409768368811d664c5a409616a7b8e1 to your computer and use it in GitHub Desktop.
Save allenyang79/e409768368811d664c5a409616a7b8e1 to your computer and use it in GitHub Desktop.
marshmallow first usage.
from collections import namedtuple
import datetime
import arrow
from marshmallow import Schema
from marshmallow import fields, post_load
class CustomField(fields.Field):
def _serialize(self, value, attr, obj):
print "_serialize", value, attr, obj
print 'context', self.context
if value is None:
return None
return value
def _deserialize(self, value, attr, data):
print "_deserialize", value, attr, data
print 'context', self.context
return value
class UserSchema(Schema):
name = fields.Str()
email = fields.Email()
foo = CustomField()
user_data = {
'name': 'Ronnie',
'email': '[email protected]',
'foo': 'oops'
}
#schema.context['request'] = request
schema = UserSchema()
schema.context['oops'] = 'oops'
income = schema.load(user_data)
outcome= schema.dump(income.data) # => <User(name='Ronnie')>
#print dir(outcome)
print outcome.data
#print dir(outcome)
print outcome.data
#print type(income), income
#print type(outcome), outcome
import datetime as dt
from marshmallow import Schema, fields, post_load
#from marshmallow import pprint
from pprint import pprint
class User(object):
def __init__(self, name, email,created_at=None):
self.name = name
self.email = email
if created_at:
self.created_at = created_at
else:
self.created_at = dt.datetime.now()
def __repr__(self):
return '<User(name={self.name!r})>'.format(self=self)
class UserSchema(Schema):
name = fields.Str()
email = fields.Email()
created_at = fields.DateTime()
@post_load
def make_user(self, data):
return User(**data)
#print data
#return data
user = User(name="Monty", email="[email protected]")
schema = UserSchema()
result = schema.dump(user) # to dict
pprint(result.data)
result = schema.dumps(user) # to json string
pprint(result.data)
user_data = {
'created_at': '2014-08-11T05:26:03.869245',
'email': u'[email protected]',
'name': u'Ken'
}
schema = UserSchema()
result = schema.load(user_data)
pprint(result.data)
pprint(type(result.data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment