Colander

2.0 · active · verified Thu Apr 16

Colander is a Python library providing a simple schema-based serialization and deserialization framework, currently at version 2.0. It allows developers to define data schemas to validate and transform data structures (like those from XML, JSON, or HTML forms) into Python objects, and vice-versa. The project is actively maintained, with a focus on stability and compatibility with modern Python versions, and typically releases updates as needed.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a schema using `colander.MappingSchema` and `colander.SchemaNode`. It shows how to use various types (String, Int) and validators (Range, Email). The example covers both deserializing incoming data, including handling validation errors via `colander.Invalid`, and serializing Python application structures back into schema-compliant data. It also illustrates the use of `colander.drop` for optional fields.

import colander

class UserSchema(colander.MappingSchema):
    name = colander.SchemaNode(colander.String())
    age = colander.SchemaNode(colander.Int(), validator=colander.Range(min=0, max=150))
    email = colander.SchemaNode(colander.String(), validator=colander.Email(), missing=colander.drop)

# --- Deserialization (Input Validation) ---

# Valid data
appstruct = {'name': 'Alice', 'age': 30, 'email': 'alice@example.com'}
schema = UserSchema()
try:
    deserialized_data = schema.deserialize(appstruct)
    print(f"Successfully deserialized: {deserialized_data}")
except colander.Invalid as e:
    print(f"Deserialization failed: {e.asdict()}")

# Invalid data (age out of range, missing required name, invalid email)
appstruct_invalid = {'name': 'Bob', 'age': 200, 'email': 'invalid-email'}
try:
    schema.deserialize(appstruct_invalid)
except colander.Invalid as e:
    print(f"Deserialization failed with errors: {e.asdict()}")

# Data with 'missing=colander.drop' field omitted
appstruct_partial = {'name': 'Charlie', 'age': 25}
try:
    deserialized_partial = schema.deserialize(appstruct_partial)
    print(f"Deserialized partial data: {deserialized_partial}")
except colander.Invalid as e:
    print(f"Deserialization of partial data failed: {e.asdict()}")

# --- Serialization (Output Generation) ---

# Python application structure
python_data = {'name': 'Dave', 'age': 40}
serialized_data = schema.serialize(python_data)
print(f"Successfully serialized: {serialized_data}")

python_data_full = {'name': 'Eve', 'age': 22, 'email': 'eve@example.com'}
serialized_data_full = schema.serialize(python_data_full)
print(f"Successfully serialized full data: {serialized_data_full}")

view raw JSON →