Marshmallow is the Python package that can serialize, deserialize and validate JSON data.
It's useful for web services when processing the incoming JSON data and responses in JSON format.
Installation
python3 -m venv .venv
source .venv/bin/activate
python3 -m pip install marshmallow
Examples
Simple Example
This example demonstrates the following features:
- Validation and deserialization using Schema.load().
- Preprocess the input data using @post_load.
from marshmallow import Schema, fields, validate, post_load
class Person(Schema):
name = fields.Str(required=True)
gender = fields.Str(required=True, validate=validate.OneOf({"male", "female", "other"}))
email = fields.Email(required=True)
registration_datetime = fields.DateTime("%Y-%m-%dT%H:%M:%S%z")
@post_load
def convert_to_utc_datetime(self, data, **kwargs):
data["registration_datetime"] = data["registration_datetime"].astimezone(datetime.timezone.utc)
return data
person_schema = Person()
>>> person_data = {"name": "Tommy", "gender": "male", "email": "tommy@example.com", "registration_datetime": "2022-07-06T08:00:00+08:00"}
>>> person_schema.load(person_data)
{'gender': 'male',
'name': 'Tommy',
'registration_datetime': datetime.datetime(2022, 7, 6, 0, 0, tzinfo=datetime.timezone.utc),
'email': 'tommy@example.com'}
>>> invalid_person_data = {"name": "Tommy", "gender": "mmale", "email": "tommy@example.com", "registration_datetime": "2022-07-06T08:00:00+08:00"}
>>> person_schema.load(invalid_person_data)
ValidationError: {'gender': ['Must be one of: female, other, male.']}

所有评论(0)