flask-inputfilter



Description
This library is a Flask extension that provides a simple way to validate and filter input data.
It allows you to define a set of rules for each field in your input data, including filters and validators.
The library also supports conditions that can be used to enforce complex validation rules.
It is designed to be straightforward to use and flexible, allowing you to create custom filters and validators as needed.
Quickstart
To use the InputFilter
class, create a new class that inherits from it and define the
fields you want to validate and filter.
There are many filters and validators available, but you can also create your own.
Installation
Using pip:
pip install flask-inputfilter
Using UV:
uv add flask-inputfilter
Using Poetry:
poetry add flask-inputfilter
There are plenty of wheels for all major environments and all supported python versions.
But if you happen to use an environment where there is no wheel prebuilt, you can use either
the python implementation or you can install flask-inputfilter
with the dependencies needed
for compilation by appending [compile]
to the installation commands above.
Note: If you do decide to recompile PQA binaries, you will need to install platform-specific C/C++
build
tools like Visual Studio, Xcode or
GNU Make (non-exhaustive list).
A more detailed guide can be found in the docs.
Definition
from flask_inputfilter import InputFilter
from flask_inputfilter.conditions import ExactlyOneOfCondition
from flask_inputfilter.enums import RegexEnum
from flask_inputfilter.filters import StringTrimFilter, ToIntegerFilter, ToNullFilter
from flask_inputfilter.validators import IsIntegerValidator, IsStringValidator, RegexValidator
class UpdateZipcodeInputFilter(InputFilter):
def __init__(self):
super().__init__()
self.add(
'id',
required=True,
filters=[ToIntegerFilter(), ToNullFilter()],
validators=[
IsIntegerValidator()
]
)
self.add(
'zipcode',
filters=[StringTrimFilter()],
validators=[
RegexValidator(
RegexEnum.POSTAL_CODE.value,
'The zipcode is not in the correct format.'
)
]
)
self.add(
'city',
filters=[StringTrimFilter()],
validators=[
IsStringValidator()
]
)
self.add_condition(
ExactlyOneOfCondition(['zipcode', 'city'])
)
Usage
To use the InputFilter
class, call the validate
method on the class instance.
After calling validate
, the validated data will be available in g.validated_data
.
If the data is invalid, a 400 response with an error message will be returned.
from flask import Flask, g
from your-path import UpdateZipcodeInputFilter
app = Flask(__name__)
@app.route('/update-zipcode', methods=['POST'])
@UpdateZipcodeInputFilter.validate()
def updateZipcode():
data = g.validated_data
id = data.get('id')
zipcode = data.get('zipcode')
city = data.get('city')
See also
For further instructions please view the documentary.
For ideas, suggestions or questions, please open an issue on GitHub.