Marshmallow Data Validation and Transformation in Python

  • Share this:

Code introduction


This function uses the Marshmallow library for data validation and loading. It first defines a user data model, including name and age fields, and sets a validation rule that the age must be 18 or older. It uses the pre_load hook to perform age validation before loading the data, and if the age is less than 18, it throws a validation error. It uses the post_load hook to perform some transformation operations after loading the data, such as returning a dictionary containing user information.


Technology Stack : Marshmallow

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
from marshmallow import Schema, fields, ValidationError, pre_load, post_load

def validate_and_load_data(data):
    class UserSchema(Schema):
        name = fields.Str(required=True)
        age = fields.Int(required=True)

        @pre_load
        def check_age(self, data, **kwargs):
            if data['age'] < 18:
                raise ValidationError("Age must be 18 or older")
            return data

        @post_load
        def make_user(self, data, **kwargs):
            return {'name': data['name'], 'age': data['age']}

    user_schema = UserSchema()
    try:
        return user_schema.load(data)
    except ValidationError as e:
        return {'error': str(e)}

# JSON representation                
              
Tags: