Python Marshmallow: Simplified O
2018-05-11 本文已影响122人
溯月_Violet
注:读书笔记而已,仅作总结、理解、补充,不作原创,谢谢。
原文地址:marshmallow: simplified object serialization
Marshmallow: converting complex datatypes (objects) to and from native Python datatypes.
- Validate input data
- Deserialize input data to app-level objects
- Serialize app-level objects to primitive python types (Dict, Json) for use in an HTTP API
Examples
import datetime
from marshmallow import Schema, fields, pprint, post_load, ValidationError
# **************************Declaring Schemas**********************
class User(object):
def __init__(self, name, email, age=25):
self.name = name
self.email = email
self.age = age
self.create_time = datetime.datetime.now()
def __report__(self):
return '<User(name=(self.name!r)>'.format(self=self)
class UserSchema(Schema):
name = fields.Str()
email = fields.Email()
age = fields.Integer()
create_time = fields.DateTime()
# **************************Serializing Objects**********************
user = User(name="Violet", email="violet@email.com")
schema = UserSchema()
# serialize to JSON
serialization_result = schema.dump(user) # serialization
pprint(serialization_result)
#Output:
#{
# "name": "Violet",
# "email": "violet@email.com",
# "age": 25
# "created_time": "2018-05-08T21:47:16.049594+00:00"
#}
# serialize to JSON-encoded String
json_string = schema.dumps(user)
pprint(json_string)
#'{"name":"Violet, "email": "violet@email.com", "age": 25, "created_time": "2018-05-08T21:47:16.049594+00:00"}'
# **************************Filtering Output**********************
filtered_schema = UserSchema(only=('name', 'email'))
filtered_schema.dump(user)
#'{"name": "Violet", "email": "violet@email.com"}'
#***************************Deserializing Objects**********************
user_data = {
"name": "Violet",
"email": "violet@email.com",
"age": 20,
"create_time": "2018-05-08T21:47:16.049594+00:00"
}
schema = UserSchema()
result = schema.load(user_data)
pprint(result)
#{
# "name": "Violet",
# "email": "violet@email.com",
# "age": 20,
# "create_time": datetime.datetime(xxxx, xx, xx, xx, xx, xx, xxxxxx)"
#}
# deserializing to objects!!!
class UserSchema(Schema):
name = fields.Str()
email = fields.Email()
age = fields.Integer()
create_time = fields.DateTime()
@post_load
def make_type(self, data):
return User(**data)
schema = UserSchema()
result = schema.load(user_data)
result
#<User(name='Violet')>
#*********************Handling Collections of Objects********************
user1 = User(name="Violet", email="violet@email.com")
user2 = User(name="Sophia", email="sophia@email.com")
users = [user1, user2]
schema = UserSchema(many=True)
result = schema.dump(users) # OR UserSchema().dump(users, many=True)
# ************************Validate Callable************************
def validate_age(age):
if age < 0:
raise ValidationError("Age must be equal or greater than 0")
class UserSchema(Schema):
name = fields.Str()
email = fields.Email()
age = fields.Integer(validate=validate_age) # if the value of age is less than 0, throw a ValidationError
create_time = fields.DateTime()
#****************OR****************
class UserSchema(Schema):
name = fields.Str()
email = fields.Email()
age = fields.Integer()
create_time = fields.DateTime()
@validates('age'):
def validate_age(self, age):
if age < 0:
raise ValidationError("Age must be equal or greater than 0")
#*****************Schema.validate**********************
errors = UserSchema().validate({"name": "Violet", "email": "whatever"}
errors
# {"email": [' "whatever" is not a valid email address.']}
Available Field Classes
- Parameters:
- default: used to set a default value for this field. If not set, the field will be discarded from serialization. May be a value or a callable.
- attribute (str): the name of the attribute to get the value from when serializing. If None, assumes the attribute has the same name as the field. -- That's why we usually take the same names of the class fields as field names!
- data_key (str): the name of the attribute to get the value from when deserializing. If None, assumes the key has the same name as the field.
-
validate (callable): Validator or collection of validators that are called during deserialization.
- callable validator: takes a field's input value as its only parameter and returns a boolean indicating the result of validation. If it returns false, an ValidationError is raised.
- required: Indicates if the field is required. Default to True (I suppose). If required=True and the field value is not provided, an ValidationError is raised.
- allow_none: Set this to True if None should be considered a valid value during validation / deserialization. Default to False!!! (except when missing=None and allow_none is unset)
- load_only: If True, skip this field during serialization. (It means this field only applicable in deserialization)
- dump_only: If True, skip this field during deserialization. (It means this field only applicable in serialization, which effectively marks the field as read-only)
- missing: Default field value for deserialization. May be a value of a callable.
- error_messages (dict): Overrides Field.default_error_messages.
- metadata: Extra arguments to be stored as metadata.
For more information, see API Docs - Fields