Creating Custom Filters

While Cion comes with a rich built in set of filters that can convert values, enforce types, and validate items, it is probable that you will want to create your own custom filter for a specialized use case.

Tutorial

All the code for this is found in examples/custom_filter.py

First, we want to create our custom filter function. For this example, we will create a validator that ensures that a list of integers is in order.

First, we need to make sure that the value passed is something that we can iterate through. Make sure to add from typing import Iterable at the top of your file.

def numbers_in_order(value: list[int]):
    if not isinstance(value, Iterable):
        raise cion.exceptions.ValidatorError("Must be a list of ints")

After that, we need to go and ensure that the list is in the proper order. As we go through the list, we need to make sure that the item we are currently comparing is an int. Then, we ignore the first item, since comparing it with the item behind it would use the last item in the list, which is not what we want. So, after we check that it isn’t the first item, we check that it is larger than the item behind it. If it is, we raise an error.

    for i in enumerate(value):
        item = value[i]

        if not isinstance(item, int):
            raise cion.exceptions.ValidatorError("Must be a list of ints")

        if i != 0:
            if item < value[i - 1]:
                raise cion.exceptions.ValidatorError("Items must be in order")

From there, we can assign the filter to a field in a schema.

schema = cion.Schema(
    fields={
        "code": cion.Field(
            filters=[numbers_in_order],
            required=True,
        )
    }
)

Once we have declared a schema, we can validate any data.

Passes
print(schema.validate({"code": [1, 2, 3, 4, 5]}))
Fails, it must be a list
try:
    schema.validate({"code": "cion"})
except cion.ValidationError as error:
    print(error)
Fails, it must be a list of integers
try:
    schema.validate({"code": ["cion"]})
except cion.ValidationError as error:
    print(error)
Fails, the list must be in order
try:
    schema.validate({"code": [5, 4, 3, 2, 1]})
except cion.ValidationError as error:
    print(error)