Python

Python Marshmallow: Simplified O

2018-05-11  本文已影响122人  溯月_Violet

注:读书笔记而已,仅作总结、理解、补充,不作原创,谢谢。
原文地址:marshmallow: simplified object serialization


Marshmallow: converting complex datatypes (objects) to and from native Python datatypes.


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

For more information, see API Docs - Fields

上一篇下一篇

猜你喜欢

热点阅读