Filter

Filters are used to filter the input data to a wanted format.

Overview

Filters can be added into the add method for a specific field or as a global filter for all fields in add_global_filter.

The global filters will be executed before the specific field filtering.

Example

class TestInputFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add(
            'username',
            required=True,
            filters=[StringTrimFilter()]
        )

        self.add(
            'name',
            required=True,
            filters=[StringTrimFilter()]
        )

        self.add_global_filter(ToLowerFilter())

Available Filters

Base Filter

class flask_inputfilter.filters.BaseFilter

Bases: object

BaseFilter-Class.

Every filter should inherit from it.

apply(value)

Apply the filter to the given value.

Parameters:

value – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Detailed Description

class flask_inputfilter.filters.ArrayElementFilter(element_filter)

Bases: BaseFilter

Filters each element in an array by applying one or more BaseFilter

Parameters:

  • element_filter (BaseFilter | list[BaseFilter]): A filter or a list of filters to apply to each element in the array.

Expected Behavior:

Validates that the input is a list and applies the specified filter(s) to each element. If any element does not conform to the expected structure, a ValueError is raised.

Example Usage:

class TagInputFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('tags', validators=[
            ArrayElementValidator(element_filter=IsStringValidator())
        ])
Parameters:

element_filter (Union[BaseFilter, list[BaseFilter]])

element_filter
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

list[Any]

class flask_inputfilter.filters.ArrayExplodeFilter(delimiter=',')

Bases: BaseFilter

Splits a string into an array based on a specified delimiter.

Parameters:

  • delimiter (str, default: ","): The delimiter used to split the string.

Expected Behavior:

If the input value is a string, it returns a list of substrings. For non-string values, it returns the value unchanged.

Example Usage:

class TagFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('tags', filters=[
            ArrayExplodeFilter(delimiter=";")
        ])
Parameters:

delimiter (str)

delimiter
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

list[str] | Any

class flask_inputfilter.filters.Base64ImageDownscaleFilter(size=None, width=None, height=None, proportionally=True)

Bases: BaseFilter

Downscales a base64-encoded image to fit within a specified size. The filter can work with both base64 strings and PIL Image objects.

Parameters:

  • size (Optional[int], default: 1024 * 1024): A rough pixel count used to compute default dimensions.

  • width (Optional[int], default: size**0.5): The target width. If not provided, it is calculated as sqrt(size).

  • height (Optional[int], default: size**0.5): The target height. If not provided, it is calculated as sqrt(size).

  • proportionally (bool, default: True): Determines if the image should be scaled proportionally. If False, the image is forcefully resized to the specified width and height.

Expected Behavior:

If the image (or its base64 representation) exceeds the target dimensions, the filter downscales it. The result is a base64-encoded string. If the image is already within bounds or if the input is not a valid image, the original value is returned.

Example Usage:

class ImageFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('profile_pic', filters=[
            Base64ImageDownscaleFilter(size=1024*1024)
        ])
Parameters:
  • size (Optional[int])

  • width (Optional[int])

  • height (Optional[int])

  • proportionally (bool)

height
proportionally
width
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

Any

static image_to_base64(image)
Parameters:

image (<module 'PIL.Image' from '/opt/hostedtoolcache/Python/3.11.13/x64/lib/python3.11/site-packages/PIL/Image.py'>)

Return type:

str

resize_picture(image)

Resizes the image if it exceeds the specified width/height and returns the base64 representation.

Parameters:

image (<module 'PIL.Image' from '/opt/hostedtoolcache/Python/3.11.13/x64/lib/python3.11/site-packages/PIL/Image.py'>)

Return type:

str

scale_image(image)

Scale the image proportionally to fit within the target width/height.

Parameters:

image (<module 'PIL.Image' from '/opt/hostedtoolcache/Python/3.11.13/x64/lib/python3.11/site-packages/PIL/Image.py'>)

Return type:

<module ‘PIL.Image’ from ‘/opt/hostedtoolcache/Python/3.11.13/x64/lib/python3.11/site-packages/PIL/Image.py’>

class flask_inputfilter.filters.Base64ImageResizeFilter(max_size=4194304, format=None, preserve_icc_profile=False, preserve_metadata=False)

Bases: BaseFilter

Reduces the file size of a base64-encoded image by resizing and compressing it.

Parameters:

  • max_size (int, default: 4 * 1024 * 1024): The maximum allowed file size in bytes.

  • format (ImageFormatEnum, default: ImageFormatEnum.JPEG): The output image format.

  • preserve_icc_profile (bool, default: False): If set to True, the ICC profile is preserved.

  • preserve_metadata (bool, default: False): If set to True, image metadata is preserved.

Expected Behavior:

The filter resizes and compresses the image iteratively until its size is below the specified maximum. The final output is a base64-encoded string of the resized image. If the input is invalid, the original value is returned.

Example Usage:

class AvatarFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('avatar', filters=[
            Base64ImageResizeFilter(max_size=4*1024*1024)
        ])
Parameters:
  • max_size (int)

  • format (Optional[ImageFormatEnum])

  • preserve_icc_profile (bool)

  • preserve_metadata (bool)

format
max_size
preserve_icc_profile
preserve_metadata
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

Any

image_to_base64(image)

Convert an image to a base64-encoded string.

Parameters:

image (<module 'PIL.Image' from '/opt/hostedtoolcache/Python/3.11.13/x64/lib/python3.11/site-packages/PIL/Image.py'>)

Return type:

str

reduce_image(image)

Reduce the size of an image by resizing and compressing it.

Parameters:

image (<module 'PIL.Image' from '/opt/hostedtoolcache/Python/3.11.13/x64/lib/python3.11/site-packages/PIL/Image.py'>)

Return type:

<module ‘PIL.Image’ from ‘/opt/hostedtoolcache/Python/3.11.13/x64/lib/python3.11/site-packages/PIL/Image.py’>

save_image_to_buffer(image, quality)

Save the image to an in-memory buffer with the specified quality.

Parameters:
  • image (Image)

  • quality (int)

Return type:

BytesIO

class flask_inputfilter.filters.BlacklistFilter(blacklist)

Bases: BaseFilter

Filters out unwanted substrings or keys based on a predefined blacklist.

Parameters:

  • blacklist (list[str]): A list of substrings (for strings) or keys (for dictionaries) that should be removed.

Expected Behavior:

  • For strings: Removes any occurrence of blacklisted items and trims whitespace.

  • For lists: Filters out items present in the blacklist.

  • For dictionaries: Removes key-value pairs where the key is blacklisted.

Example Usage:

class CommentFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('comment', filters=[
            BlacklistFilter(blacklist=["badword1", "badword2"])
        ])
Parameters:

blacklist (list[str])

blacklist
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

Any

class flask_inputfilter.filters.StringRemoveEmojisFilter

Bases: BaseFilter

Removes emojis from a string using regular expression matching.

Expected Behavior:

If the input is a string, all emoji characters are removed; non-string inputs are returned unchanged.

Example Usage:

class CommentFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('comment', filters=[
            StringRemoveEmojisFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

str | None | Any

class flask_inputfilter.filters.StringSlugifyFilter

Bases: BaseFilter

Converts a string into a slug format.

Expected Behavior:

Normalizes Unicode, converts to ASCII, lowercases the string, and replaces spaces with hyphens, producing a URL-friendly slug.

Example Usage:

class PostFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('title', filters=[
            StringSlugifyFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

str | None | Any

class flask_inputfilter.filters.StringTrimFilter

Bases: BaseFilter

Removes leading and trailing whitespace from a string.

Expected Behavior:

If the input is a string, it returns the trimmed version. Otherwise, the value remains unchanged.

Example Usage:

class UserFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('username', filters=[
            StringTrimFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

str | Any

class flask_inputfilter.filters.ToAlphaNumericFilter

Bases: BaseFilter

Ensures that a string contains only alphanumeric characters by removing all non-word characters.

Expected Behavior:

Strips out any character that is not a letter, digit, or underscore from the input string.

Example Usage:

class CodeFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('code', filters=[
            ToAlphaNumericFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

str | None | Any

class flask_inputfilter.filters.ToBase64ImageFilter(format=None, quality=85)

Bases: BaseFilter

Converts an image to a base64 encoded string. Supports various input formats including file paths, bytes, or PIL Image objects.

Parameters:

  • format (ImageFormatEnum, default: ImageFormatEnum.PNG): The output image format for the base64 encoding.

  • quality (int, default: 85): The image quality (1-100) for lossy formats like JPEG. Higher values mean better quality.

Expected Behavior:

Converts the input image to a base64 encoded string: - If input is a PIL Image object, converts it directly - If input is a string, tries to open it as a file path - If input is bytes, tries to open as image data - If input is already a base64 string, validates and returns it - Returns the original value if conversion fails

Example Usage:

class ImageFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('image', filters=[
            ToBase64ImageFilter(format=ImageFormatEnum.JPEG)
        ])
Parameters:
  • format (Optional[ImageFormatEnum])

  • quality (int)

format
quality
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

Any

class flask_inputfilter.filters.ToBooleanFilter

Bases: BaseFilter

Converts the input value to a boolean.

Expected Behavior:

Uses Python’s built-in bool() conversion. Note that non-empty strings and non-zero numbers will return True.

Example Usage:

class ActiveFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('active', filters=[
            ToBooleanFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

bool | None | Any

class flask_inputfilter.filters.ToCamelCaseFilter

Bases: BaseFilter

Transforms a string into camelCase format.

Expected Behavior:

Normalizes delimiters such as spaces, underscores, or hyphens, capitalizes each word (except the first), and concatenates them so that the first letter is lowercase.

Example Usage:

class IdentifierFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('identifier', filters=[
            ToCamelCaseFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

str | Any

class flask_inputfilter.filters.ToDataclassFilter(dataclass_type)

Bases: BaseFilter

Converts a dictionary to a specified dataclass.

Parameters:

  • dataclass_type (Type[dict]): The target dataclass type that the dictionary should be converted into.

Expected Behavior:

If the input is a dictionary, it instantiates the provided dataclass using the dictionary values. Otherwise, the input is returned unchanged.

Example Usage:

from my_dataclasses import MyDataClass

class DataFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('data', filters=[
            ToDataclassFilter(MyDataClass)
        ])
Parameters:

dataclass_type (Type[dict])

dataclass_type
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

Any

class flask_inputfilter.filters.ToDateFilter

Bases: BaseFilter

Converts an input value to a date object. Supports ISO 8601 formatted strings and datetime objects.

Expected Behavior:

  • If the input is a datetime, returns the date portion.

  • If the input is a string, attempts to parse it as an ISO 8601 date.

  • Returns the original value if conversion fails.

Example Usage:

class BirthdateFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('birthdate', filters=[
            ToDateFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

date | Any

class flask_inputfilter.filters.ToDateTimeFilter

Bases: BaseFilter

Converts an input value to a datetime object. Supports ISO 8601 formatted strings.

Expected Behavior:

  • If the input is a datetime, it is returned unchanged.

  • If the input is a date, it is combined with a minimum time value.

  • If the input is a string, the filter attempts to parse it as an ISO 8601 datetime.

  • If conversion fails, the original value is returned.

Example Usage:

class TimestampFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('timestamp', filters=[
            ToDateTimeFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

datetime | Any

class flask_inputfilter.filters.ToDigitsFilter

Bases: BaseFilter

Converts a string to a numeric type (either an integer or a float).

Expected Behavior:

  • If the input string matches an integer pattern, it returns an integer.

  • If it matches a float pattern, it returns a float.

  • Otherwise, the input is returned unchanged.

Example Usage:

class QuantityFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('quantity', filters=[
            ToDigitsFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

float | int | Any

class flask_inputfilter.filters.ToEnumFilter(enum_class)

Bases: BaseFilter

Converts a value to an instance of a specified Enum.

Parameters:

  • enum_class (Type[Enum]): The enum class to which the input should be converted.

Expected Behavior:

  • If the input is a string or an integer, the filter attempts to convert it into the corresponding enum member.

  • If the input is already an enum instance, it is returned as is.

  • If conversion fails, the original input is returned.

Example Usage:

from my_enums import ColorEnum

class ColorFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('color', filters=[
            ToEnumFilter(ColorEnum)
        ])
Parameters:

enum_class (Type[Enum])

enum_class
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

Enum | Any

class flask_inputfilter.filters.ToFloatFilter

Bases: BaseFilter

Converts the input value to a float.

Expected Behavior:

  • Attempts to cast the input using float().

  • On a ValueError or TypeError, returns the original value.

Example Usage:

class PriceFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('price', filters=[
            ToFloatFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

float | Any

class flask_inputfilter.filters.ToImageFilter

Bases: BaseFilter

Converts various input formats to a PIL Image object. Supports file paths, base64 encoded strings, and bytes.

Expected Behavior:

Converts the input to a PIL Image object: - If input is already a PIL Image object, returns it as-is - If input is a string, tries to open it as a file path or decode as base64 - If input is bytes, tries to open as image data - Returns the original value if conversion fails

Example Usage:

class ImageFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('image', filters=[
            ToImageFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

Any

class flask_inputfilter.filters.ToIntegerFilter

Bases: BaseFilter

Converts the input value to an integer.

Expected Behavior:

  • Attempts to cast the input using int().

  • On failure, returns the original value.

Example Usage:

class AgeFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('age', filters=[
            ToIntegerFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

int | Any

class flask_inputfilter.filters.ToIsoFilter

Bases: BaseFilter

Converts a date or datetime object to an ISO 8601 formatted string.

Expected Behavior:

  • If the input is a date or datetime, returns its ISO 8601 string.

  • Otherwise, returns the original value.

Example Usage:

class TimestampIsoFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('timestamp', filters=[
            ToIsoFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

str | Any

class flask_inputfilter.filters.ToLowerFilter

Bases: BaseFilter

Converts a string to lowercase.

Expected Behavior:

  • For string inputs, returns the lowercase version.

  • Non-string inputs are returned unchanged.

Example Usage:

class UsernameFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('username', filters=[
            ToLowerFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

str | Any

class flask_inputfilter.filters.ToNormalizedUnicodeFilter(form=None)

Bases: BaseFilter

Normalizes a Unicode string to a specified form.

Parameters:

  • form (UnicodeFormEnum, default: UnicodeFormEnum.NFC): The target Unicode normalization form.

Expected Behavior:

  • Removes accent characters and normalizes the string based on the specified form.

  • Returns non-string inputs unchanged.

Example Usage:

class TextFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('text', filters=[
            ToNormalizedUnicodeFilter(form="NFKC")
        ])
Parameters:

form (Optional[UnicodeFormEnum])

form
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

str | Any

class flask_inputfilter.filters.ToNullFilter

Bases: BaseFilter

Transforms the input to None if it is an empty string or already None.

Expected Behavior:

  • If the input is "" or None, returns None.

  • Otherwise, returns the original value.

Example Usage:

class MiddleNameFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('middle_name', filters=[
            ToNullFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

Any | None

class flask_inputfilter.filters.ToPascalCaseFilter

Bases: BaseFilter

Converts a string to PascalCase.

Expected Behavior:

  • Capitalizes the first letter of each word and concatenates them without spaces.

  • Returns non-string inputs unchanged.

Example Usage:

class ClassNameFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('class_name', filters=[
            ToPascalCaseFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

str | None | Any

class flask_inputfilter.filters.ToSnakeCaseFilter

Bases: BaseFilter

Converts a string to snake_case.

Expected Behavior:

  • Inserts underscores before uppercase letters (except the first), converts the string to lowercase, and replaces spaces or hyphens with underscores.

  • Non-string inputs are returned unchanged.

Example Usage:

class VariableFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('variableName', filters=[
            ToSnakeCaseFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

str | Any

class flask_inputfilter.filters.ToStringFilter

Bases: BaseFilter

Converts any input value to its string representation.

Expected Behavior:

  • Uses Python’s built-in str() to convert the input to a string.

Example Usage:

class IdFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('id', filters=[
            ToStringFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

str | Any

class flask_inputfilter.filters.ToTypedDictFilter(typed_dict)

Bases: BaseFilter

Converts a dictionary into an instance of a specified TypedDict.

Parameters:

  • typed_dict (Type[TypedDict]): The target TypedDict type.

Expected Behavior:

  • If the input is a dictionary, returns an instance of the specified TypedDict.

  • Otherwise, returns the original value.

Example Usage:

class ConfigFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('config', filters=[
            ToTypedDictFilter(MyTypedDict)
        ])
Parameters:

typed_dict (Type[TypedDict]) – The TypedDict class to convert the dictionary to.

typed_dict
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

Any

class flask_inputfilter.filters.ToUpperFilter

Bases: BaseFilter

Converts a string to uppercase.

Expected Behavior:

  • For string inputs, returns the uppercase version.

  • Non-string inputs are returned unchanged.

Example Usage:

class CodeFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('code', filters=[
            ToUpperFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (str) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

str | Any

class flask_inputfilter.filters.TruncateFilter(max_length)

Bases: BaseFilter

Truncates a string to a specified maximum length.

Parameters:

  • max_length (int): The maximum allowed length of the string.

Expected Behavior:

  • If the string exceeds the specified length, it is truncated.

  • Non-string inputs are returned unchanged.

Example Usage:

class DescriptionFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('description', filters=[
            TruncateFilter(max_length=100)
        ])
Parameters:

max_length (int)

max_length
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

str | Any

class flask_inputfilter.filters.WhitelistFilter(whitelist=None)

Bases: BaseFilter

Filters the input by only keeping elements that appear in a predefined whitelist.

Parameters:

  • whitelist (list[str], optional): A list of allowed words or keys. If not provided, no filtering is applied.

Expected Behavior:

  • For strings: Splits the input by whitespace and returns only the words present in the whitelist.

  • For lists: Returns a list of items that are in the whitelist.

  • For dictionaries: Returns a dictionary containing only the

    whitelisted keys.

Example Usage:

class RolesFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('roles', filters=[
            WhitelistFilter(whitelist=["admin", "user"])
        ])
Parameters:

whitelist (Optional[list[str]])

whitelist
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

Any

class flask_inputfilter.filters.WhitespaceCollapseFilter

Bases: BaseFilter

Collapses multiple consecutive whitespace characters into a single space.

Expected Behavior:

  • Replaces sequences of whitespace with a single space and trims the result.

  • Non-string inputs are returned unchanged.

Example Usage:

class AddressFilter(InputFilter):
    def __init__(self):
        super().__init__()

        self.add('address', filters=[
            WhitespaceCollapseFilter()
        ])
apply(value)

Apply the filter to the given value.

Parameters:

value (Any) – The value to apply the filter to.

Returns:

The filtered value.

Raises:

NotImplementedError – If the method is not implemented by subclasses.

Return type:

str | Any