Flaxon 0.3.0 and Teloce-Py 0.3.0 are available on PyPI. Release instructions are maintained on this site; source links identify the framework snapshot. Check version and upgrade guidance.

Framework source · Markdown

Validation API

Schema

Base schema class for data validation.

Constructor

class Schema(metaclass=SchemaMeta):
    __fields__: dict[str, Field]
````

---

## Class Methods

### load

```python
@classmethod
def load(cls, data: Any) -> Schema

Load and validate data from a dictionary.

Parameter Type Description
data Any Data to validate (must be a dictionary)

Raises:

ValidationError if validation fails.

Returns:

A schema instance with validated data.

Example:

user = CreateUser.load({
    "name": "Alice",
    "email": "alice@example.com"
})

Methods

to_dict

def to_dict(self) -> dict[str, Any]

Convert schema to a dictionary.

Example:

data = user.to_dict()

# {
#   "name": "Alice",
#   "email": "alice@example.com"
# }

to_json

def to_json(self) -> dict[str, Any]

Convert schema to a JSON serializable dictionary.

Example:

json_data = user.to_json()

validate

def validate(self) -> None

Validate schema data manually.

Raises:

ValidationError if validation fails.


Fields

StrField

String field with validation options.

StrField(
    *,
    required: bool = False,
    default: Any = None,
    nullable: bool = False,
    min_length: int | None = None,
    max_length: int | None = None,
    strip: bool = True,
    pattern: str | None = None,
)
Parameter Type Description
required bool Field must be present
default Any Default value if missing
nullable bool Allow null values
min_length int None
max_length int None
strip bool Remove whitespace
pattern str None

Example:

name = fields.StrField(
    required=True,
    min_length=2,
    max_length=80
)

IntField

Integer field with range validation.

IntField(
    *,
    required: bool = False,
    default: Any = None,
    nullable: bool = False,
    minimum: int | None = None,
    maximum: int | None = None,
)
Parameter Type Description
minimum int None
maximum int None

Example:

age = fields.IntField(
    minimum=13,
    maximum=120
)

FloatField

Float field with range validation.

FloatField(
    *,
    required: bool = False,
    default: Any = None,
    nullable: bool = False,
    minimum: float | None = None,
    maximum: float | None = None,
)

Example:

price = fields.FloatField(
    minimum=0.0,
    maximum=9999.99
)

BoolField

Boolean field.

BoolField(
    *,
    required: bool = False,
    default: Any = None,
    nullable: bool = False,
)

Example:

active = fields.BoolField(default=True)

ChoiceField

Field with allowed values.

ChoiceField(
    choices: list[Any] | tuple[Any, ...] | set[Any],
    *,
    required: bool = False,
    default: Any = None,
    nullable: bool = False,
)
Parameter Type Description
choices list tuple

Example:

status = fields.ChoiceField(
    ["pending", "active", "deleted"],
    default="pending"
)

EmailField

Email validation field.

EmailField(
    *,
    required: bool = False,
    default: Any = None,
    nullable: bool = False,
    min_length: int | None = None,
    max_length: int | None = None,
)

Example:

email = fields.EmailField(required=True)

DateField

Date validation field.

DateField(
    *,
    required: bool = False,
    default: Any = None,
    nullable: bool = False,
    format: str = "%Y-%m-%d",
)
Parameter Type Description
format str Date format string

Example:

birthday = fields.DateField(
    format="%Y-%m-%d"
)

DateTimeField

Datetime validation field.

DateTimeField(
    *,
    required: bool = False,
    default: Any = None,
    nullable: bool = False,
    format: str = "%Y-%m-%dT%H:%M:%S",
)

Example:

created_at = fields.DateTimeField(
    format="%Y-%m-%dT%H:%M:%S"
)

DecimalField

Decimal validation field.

DecimalField(
    *,
    required: bool = False,
    default: Any = None,
    nullable: bool = False,
    minimum: Decimal | None = None,
    maximum: Decimal | None = None,
    places: int | None = None,
)
Parameter Type Description
places int None

Example:

amount = fields.DecimalField(
    minimum=0,
    places=2
)

UUIDField

UUID validation field.

UUIDField(
    *,
    required: bool = False,
    default: Any = None,
    nullable: bool = False,
)

Example:

token = fields.UUIDField(required=True)

ListField

List field with item validation.

ListField(
    item_field: Field | None = None,
    *,
    required: bool = False,
    default: Any = None,
    nullable: bool = False,
    min_items: int | None = None,
    max_items: int | None = None,
)
Parameter Type Description
item_field Field None
min_items int None
max_items int None

Example:

tags = fields.ListField(
    fields.StrField(min_length=1),
    min_items=1,
    max_items=10
)

NestedField

Nested schema field.

NestedField(
    schema_class: type[Schema],
    *,
    required: bool = False,
    default: Any = None,
    nullable: bool = False,
)

Example:

class AddressSchema(Schema):
    street = fields.StrField(required=True)
    city = fields.StrField(required=True)


class UserSchema(Schema):
    name = fields.StrField(required=True)
    address = fields.NestedField(AddressSchema)

AnyField

Accepts any value.

AnyField(
    *,
    required: bool = False,
    default: Any = None,
    nullable: bool = False,
)

Example:

metadata = fields.AnyField()

Exceptions

ValidationError

Raised when validation fails.

ValidationError(
    fields: dict[str, list[str]]
)
Attribute Type Description
fields dict[str, list[str]] Field error messages

Example:

try:
    user = CreateUser.load(data)

except ValidationError as exc:
    print(exc.fields)

FieldError

Raised when a field validation fails.

FieldError(message: str)
Attribute Type Description
message str Error message

Complete Example

from flaxon.validation import Schema, fields
from flaxon.validation.validators import (
    custom_validator,
    and_validators,
    pattern_validator,
)


def validate_unique_email(value, field):
    if value == "admin@example.com":
        raise FieldError("Email already registered")


class CreateUser(Schema):
    username = fields.StrField(
        required=True,
        min_length=3,
        max_length=30,
        validators=[
            and_validators(
                pattern_validator(
                    r"^[a-zA-Z0-9_]+$"
                )
            )
        ],
    )

    email = fields.EmailField(
        required=True,
        validators=[
            custom_validator(validate_unique_email)
        ],
    )

    password = fields.StrField(
        required=True,
        min_length=8,
        max_length=128,
    )

    age = fields.IntField(
        required=False,
        minimum=13,
        maximum=120,
    )

    role = fields.ChoiceField(
        ["user", "moderator", "admin"],
        default="user",
    )

    tags = fields.ListField(
        fields.StrField(min_length=1),
        max_items=10,
    )


@app.post("/users")
async def create_user(data: CreateUser):
    return {
        "user": data.to_dict()
    }

Use this capability in a full-stack app

Flaxon serves Python APIs and Teloce interfaces in one project. Keep validation, authorization and privileged operations on the server; components call those endpoints and present their results. Follow the full-stack lessons and Teloce integration reference to connect this capability to pages, components and application modules.