UD - FLASK - Serialization

why serialization

  • easier serialization / deserialization

  • separate model from data interaction

  • whitelist params

json & reqparse are no longer required.

1. Vanilla marshmallow

core

from marshmallow import Schema, fields

class BookSchema(Schema):
    title = fields.Str()
    author = fields.Str()

class Book:
    def __init__(self, title, author, description):
        self.title = title
        self.author = author
        self.description = description

1.1. Serialization -> dict

1.2. Deserialization -> object

2. Flask-marshmallow

  1. schema will load json to object directly.

  2. tight integration between schema & model; fields only declare in one place.

  3. init& json methods are no longer required in model.

  4. reqparse method is no longer required in resource.

2.1. Components

model (no marshmallow here)

schema (fields are defined by models)

resource

2.2. Nested schema

Last updated

Was this helpful?