InputFilter

Overview

class flask_inputfilter.input_filter.InputFilter(methods=None)

Bases: object

Base class for all input filters.

Parameters:

methods (Optional[list[str]])

is_valid()

Checks if the object’s state or its attributes meet certain conditions to be considered valid. This function is typically used to ensure that the current state complies with specific requirements or rules.

Returns:

Returns True if the state or attributes of the object fulfill

all required conditions; otherwise, returns False.

Return type:

bool

classmethod validate()

Decorator for validating input data in routes.

Parameters:

cls

Returns:

Callable

Return type:

Callable

validate_data(data=None)

Validates input data against defined field rules, including applying filters, validators, custom logic steps, and fallback mechanisms. The validation process also ensures the required fields are handled appropriately and conditions are checked after processing.

Parameters:

data (dict[str, Any]) – A dictionary containing the input data to be validated where keys represent field names and values represent the corresponding data.

Returns:

A dictionary containing the

validated data with any modifications, default values, or processed values as per the defined validation rules.

Return type:

Union[dict[str, Any], Type[T]]

Raises:

Any errors raised during external API calls, validation, or – logical steps execution of the respective fields or conditions will propagate without explicit handling here.

add_condition(condition)

Add a condition to the input filter.

Parameters:

condition (BaseCondition) – The condition to add.

Return type:

None

get_conditions()

Retrieve the list of all registered conditions.

This function provides access to the conditions that have been registered and stored. Each condition in the returned list is represented as an instance of the BaseCondition type.

Returns:

A list containing all currently registered

instances of BaseCondition.

Return type:

list[BaseCondition]

set_data(data)

Filters and sets the provided data into the object’s internal storage, ensuring that only the specified fields are considered and their values are processed through defined filters.

Parameters:

data (dict[str, Any]) – The input dictionary containing key-value pairs where keys represent field names and values represent the associated data to be filtered and stored.

Return type:

None

get_value(name)

This method retrieves a value associated with the provided name. It searches for the value based on the given identifier and returns the corresponding result. If no value is found, it typically returns a default or fallback output. The method aims to provide flexibility in retrieving data without explicitly specifying the details of the underlying implementation.

Parameters:

name (str) – A string that represents the identifier for which the corresponding value is being retrieved. It is used to perform the lookup.

Returns:

The retrieved value associated with the given name. The

specific type of this value is dependent on the implementation and the data being accessed.

Return type:

Any

get_values()

Retrieves a dictionary of key-value pairs from the current object. This method provides access to the internal state or configuration of the object in a dictionary format, where keys are strings and values can be of various types depending on the object’s design.

Returns:

A dictionary containing string keys and their

corresponding values of any data type.

Return type:

dict[str, Any]

get_raw_value(name)

Fetches the raw value associated with the provided key.

This method is used to retrieve the underlying value linked to the given key without applying any transformations or validations. It directly fetches the raw stored value and is typically used in scenarios where the raw data is needed for processing or debugging purposes.

Parameters:

name (str) – The name of the key whose raw value is to be retrieved.

Returns:

The raw value associated with the provided key.

Return type:

Any

get_raw_values()

Retrieves raw values from a given source and returns them as a dictionary.

This method is used to fetch and return unprocessed or raw data in the form of a dictionary where the keys are strings, representing the identifiers, and the values are of any data type.

Returns:

A dictionary containing the raw values retrieved.

The keys are strings representing the identifiers, and the values can be of any type, depending on the source being accessed.

Return type:

dict[str, Any]

get_unfiltered_data()

Fetches unfiltered data from the data source.

This method retrieves data without any filtering, processing, or manipulations applied. It is intended to provide raw data that has not been altered since being retrieved from its source. The usage of this method should be limited to scenarios where unprocessed data is required, as it does not perform any validations or checks.

Returns:

The unfiltered, raw data retrieved from the

data source. The return type may vary based on the specific implementation of the data source.

Return type:

dict[str, Any]

set_unfiltered_data(data)

Sets unfiltered data for the current instance. This method assigns a given dictionary of data to the instance for further processing. It updates the internal state using the provided data.

Parameters:

data (dict[str, Any]) – A dictionary containing the unfiltered data to be associated with the instance.

Return type:

None

has_unknown()

Checks whether any values in the current data do not have corresponding configurations in the defined fields.

Returns:

True if there are any unknown fields; False otherwise.

Return type:

bool

get_error_message(field_name)

Retrieves and returns a predefined error message.

This method is intended to provide a consistent error message to be used across the application when an error occurs. The message is predefined and does not accept any parameters. The exact content of the error message may vary based on specific implementation, but it is designed to convey meaningful information about the nature of an error.

Parameters:

field_name (str) – The name of the field for which the error message is being retrieved.

Returns:

A string representing the predefined error message.

Return type:

Optional[str]

get_error_messages()

Retrieves all error messages associated with the fields in the input filter.

This method aggregates and returns a dictionary of error messages where the keys represent field names, and the values are their respective error messages.

Returns:

A dictionary containing field names as keys and

their corresponding error messages as values.

Return type:

dict[str, str]

add(name, required=False, default=None, fallback=None, filters=None, validators=None, steps=None, external_api=None, copy=None)

Add the field to the input filter.

Parameters:
  • name (str) – The name of the field.

  • required (Optional[bool]) – Whether the field is required.

  • default (Optional[Any]) – The default value of the field.

  • fallback (Optional[Any]) – The fallback value of the field, if validations fails or field None, although it is required.

  • filters (Optional[list[BaseFilter]]) – The filters to apply to the field value.

  • validators (Optional[list[BaseValidator]]) – The validators to apply to the field value.

  • steps (Optional[list[Union[BaseFilter, BaseValidator]]]) – Allows to apply multiple filters and validators in a specific order.

  • external_api (Optional[ExternalApiConfig]) – Configuration for an external API call.

  • copy (Optional[str]) – The name of the field to copy the value from.

Return type:

None

has(field_name)

This method checks the existence of a specific field within the input filter values, identified by its field name. It does not return a value, serving purely as a validation or existence check mechanism.

Parameters:

field_name (str) – The name of the field to check for existence.

Returns:

True if the field exists in the input filter,

otherwise False.

Return type:

bool

get_input(field_name)

Represents a method to retrieve a field by its name.

This method allows fetching the configuration of a specific field within the object, using its name as a string. It ensures compatibility with various field names and provides a generic return type to accommodate different data types for the fields.

Parameters:

field_name (str) – A string representing the name of the field who needs to be retrieved.

Returns:

The field corresponding to the

specified name.

Return type:

Optional[FieldModel]

get_inputs()

Retrieve the dictionary of input fields associated with the object.

Returns:

Dictionary containing field names as

keys and their corresponding FieldModel instances as values

Return type:

dict[str, FieldModel]

remove(field_name)

Removes the specified field from the instance or collection.

This method is used to delete a specific field identified by its name. It ensures the designated field is removed entirely from the relevant data structure. No value is returned upon successful execution.

Parameters:

field_name (str) – The name of the field to be removed.

Returns:

The value of the removed field, if any.

Return type:

Any

count()

Counts the total number of elements in the collection.

This method returns the total count of elements stored within the underlying data structure, providing a quick way to ascertain the size or number of entries available.

Returns:

The total number of elements in the collection.

Return type:

int

replace(name, required=False, default=None, fallback=None, filters=None, validators=None, steps=None, external_api=None, copy=None)

Replaces a field in the input filter.

Parameters:
  • name – The name of the field.

  • required (bool)

  • default (Any)

  • fallback (Any)

  • filters (Optional[list[BaseFilter]])

  • validators (Optional[list[BaseValidator]])

  • steps (Optional[list[Union[BaseFilter, BaseValidator]]])

  • external_api (Optional[ExternalApiConfig])

  • copy (Optional[str])

Return type:

None

add_global_filter(filter)

Add a global filter to be applied to all fields.

Parameters:

filter (BaseFilter) – The filter to add.

Return type:

None

get_global_filters()

Retrieve all global filters associated with this InputFilter instance.

This method returns a list of BaseFilter instances that have been added as global filters. These filters are applied universally to all fields during data processing.

Returns:

A list of global filters.

Return type:

list[BaseFilter]

clear()

Resets all fields of the InputFilter instance to their initial empty state.

This method clears the internal storage of fields, conditions, filters, validators, and data, effectively resetting the object as if it were newly initialized.

Return type:

None

merge(other)

Merges another InputFilter instance intelligently into the current instance.

  • Fields with the same name are merged recursively if possible,

    otherwise overwritten.

  • Conditions are combined and duplicated.

  • Global filters and validators are merged without duplicates.

Parameters:

other (InputFilter) – The InputFilter instance to merge.

Return type:

None

set_model(model_class)

Set the model class for serialization.

Parameters:

model_class (Type[T]) – The class to use for serialization.

Return type:

None

serialize()

Serialize the validated data. If a model class is set, returns an instance of that class, otherwise returns the raw validated data.

Returns:

The serialized data.

Return type:

Union[dict[str, Any], T]

add_global_validator(validator)

Add a global validator to be applied to all fields.

Parameters:

validator (BaseValidator) – The validator to add.

Return type:

None

get_global_validators()

Retrieve all global validators associated with this InputFilter instance.

This method returns a list of BaseValidator instances that have been added as global validators. These validators are applied universally to all fields during validation.

Returns:

A list of global validators.

Return type:

list[BaseValidator]

Configuration

The add method supports several options:

Name

The name option specifies the name of the field. This is the key that will be used to access the field value in the validated data.

Required

The required option specifies whether the field must be included in the input data. If the field is missing, a ValidationError will be raised with an appropriate error message.

Filters

The filters option allows you to specify one or more filters to apply to the field value. Filters are applied in the order they are defined.

For more information view the Filter documentation.

Validators

The validators option allows you to specify one or more validators to apply to the field value. Validators are applied in the order they are defined.

For more information view the Validator documentation.

Default

The default option allows you to specify a default value to use if the field is not present in the input data.

Fallback

The fallback option specifies a value to use if validation fails or required data is missing. Note that if the field is optional and absent, fallback will not apply; use default in such cases.

Steps

The steps option allows you to specify a list of different filters and validator to apply to the field value. It respects the order of the list.

ExternalApi

The external_api option allows you to specify an external API to call for the field value. The API call is made when the field is validated, and the response is used as the field value.

For more information view the ExternalApi documentation.

Copy

The copy option allows you to copy the value of another field. The copied value can be filtered and validated, due to the coping being executed first.

For more information view the Copy documentation.

Examples

Least config

Full config