flask-inputfilter documentation
Overview
Available functions:
Tip
Thank you for using flask-inputfilter!
If you have any questions or suggestions, please feel free to open an issue on GitHub. If you don’t want to miss any updates, please star the repository. This will help me to understand how many people are interested in this project.
Note
If you like the project, please consider giving it a star on GitHub.
Installation
pip install flask-inputfilter
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 numerous filters and validators available, but you can also create your own.
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
# Do something with validated data
id = data.get('id')
zipcode = data.get('zipcode')
city = data.get('city')