Random Schema Validation with Marshmallow

  • Share this:

Code introduction


This code defines a Marshmallow Schema with a single field of a randomly chosen type. It then attempts to validate the data with the schema, and if the data does not conform to the schema definition, a validation error is raised.


Technology Stack : Marshmallow

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
from marshmallow import Schema, fields, ValidationError
import random

def random_schema_validation():
    # Define a random field type
    field_type = random.choice([fields.String(), fields.Integer(), fields.Float(), fields.Dict()])

    # Create a simple schema with a single field
    class RandomSchema(Schema):
        random_field = field_type()

    # Create an instance of the schema
    schema = RandomSchema()

    # Generate a random data that might not validate
    random_data = {field: random.choice([str(i), i, float(i), {str(i): i}]) for i in range(5)}

    # Try to validate the data
    try:
        validated_data = schema.load(random_data)
        print("Data validated successfully:", validated_data)
    except ValidationError as err:
        print("Validation error:", err.messages)

# Code JSON                
              
Tags: