Skip to main content

Flask request validation

Project description

Flask Validator

Flask Validator is a powerful package designed to simplify data validation in Flask applications. It provides an easy-to-use interface for defining data validation rules and seamlessly integrates with Flask routes using a custom decorator.

  • Simplified Data Validation: Flask Validator streamlines the process of validating data in Flask applications, reducing the complexity and boilerplate code.
  • Integration with Flask Routes: The package seamlessly integrates with Flask routes through a custom decorator, making it easy to apply validation rules to specific endpoints.
  • Flexible Validation Schema: Flask Validator allows you to define validation rules using a schema structure, providing a clear and organized way to specify the expected data format.
  • Custom Validators: You can create custom validators to extend the validation capabilities of Flask Validator, enabling you to implement complex validation logic tailored to your application's needs.
  • Error Handling: Flask Validator automatically generates error messages based on the defined validation rules, simplifying the process of handling validation failures and providing

Size Limit CLI

With the help of Flask Validator, you can ensure the integrity and consistency of the data submitted to your Flask endpoints, enhancing the reliability and security of your application.

How It Works

  1. Flask Validator provides a custom decorator, @validate_form, which can be applied to Flask routes.
  2. The decorator takes a validation schema as its argument, defined using the Schema class and Field class from Flask Validator.
  3. The validation schema specifies the structure of the expected data and the validation rules for each field.
  4. When a request is made to a decorated route, Flask Validator automatically validates the incoming data based on the defined schema.
  5. If the data passes the validation, the route handler function is executed as usual.
  6. If the data fails the validation, Flask Validator generates error messages based on the defined rules and returns a response with the error details.

Usage

To use Flask Validator in your Flask application, follow these steps:

Installation

You can install Flask Validator using pip:

pip install flask_validators

Getting Started

  1. Import the necessary modules and classes from Flask Validator:
from flask import Flask, request, jsonify
from flask_validators import validate_form
  1. Create a Flask application instance:
app = Flask(__name__)
  1. Define a route with the @validate_form decorator and specify the validation schema:
@app.route('/validate', methods=['POST'])
@validate_form('age', 'name', 'email')
def validate_data():
    return jsonify({'success': True, 'message': 'Data is valid.'})
  1. Run the Flask application:
if __name__ == '__main__':
    app.run(debug=True)

Now, when a POST request is made to the /validate endpoint, Flask Validator will automatically validate the incoming data based on the specified schema. The @validate_form decorator is used to validate the fields 'age', 'name', and 'email'. If the data passes the validation, the route handler function (validate_data in this case) will be executed. Otherwise, Flask Validator will generate error messages and return a response with the error details.

You can also define Validators with specific requirements

@app.route('/validate', methods=['POST'])
@validate_form(
    Schema({
        'email': Field(required=True, type='string', validators=[
            {'name': 'email', 'message': 'Invalid email address.'}
        ])
    })
)
def validate_data():
    return jsonify({'success': True, 'message': 'Data is valid.'})

Validation Schema

The validation schema is defined using the Schema class, which takes a dictionary representing the schema structure. Each field in the schema is associated with a set of validation rules. For example, the following schema validates an email field:

Schema({
    'email': Field(required=True, type='string', validators=[
        {'name': 'email', 'message': 'Invalid email address.'}
    ])
})

In the example above, the email field is marked as required and expects a string value. It also applies an additional validator to check if the value is a valid email address.

Validation Rules

Validation rules are defined using the Field class. Each field can have properties such as required (indicating if the field is required), type (specifying the expected data type), and validators (a list of additional validators to apply).

The Field class also provides built-in validation methods, such as validate_email, validate_age, validate_name, validate_password, and validate_json. These methods can be used directly or extended to implement custom validation logic.

Custom Validators

Flask Validator allows you to create custom validators to implement complex validation logic tailored to your application's needs. To create a custom validator, define a method within the Schema class that follows the validate_<validator_name> naming convention. This method should accept the field value and any additional arguments defined in the validation rule. It should return a tuple with a boolean indicating the validation result and an error message if the validation fails.

For example, to create a custom validator named validate_custom, add the following method to the Schema class:

def validate_custom(self, value, argument1, argument2, ...):
    # Validation logic
    if valid:
        return True, None
    else:
        return False, 'Validation failed.'

Error Handling

If validation fails, Flask Validator automatically generates error messages based on the defined validation rules. The error response includes a JSON object with the field names as keys and the corresponding error messages as values. This makes it easier to handle validation failures and provide meaningful feedback to the users.

Error Handling

If validation fails, Flask Validator automatically generates error messages based on the defined validation rules. The error response includes a JSON object with the field names as keys and the corresponding error messages as values. This makes it easier to handle validation failures and provide meaningful feedback to the users.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

flask_validators-0.2.tar.gz (9.1 kB view details)

Uploaded Source

Built Distribution

flask_validators-0.2-py3-none-any.whl (15.9 kB view details)

Uploaded Python 3

File details

Details for the file flask_validators-0.2.tar.gz.

File metadata

  • Download URL: flask_validators-0.2.tar.gz
  • Upload date:
  • Size: 9.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.3

File hashes

Hashes for flask_validators-0.2.tar.gz
Algorithm Hash digest
SHA256 a0f76534f423cfe3df6a42b196df25830c320a1da4baf23886dc268504702a4c
MD5 4222d902b1a93954db4613f8bcdbc0c7
BLAKE2b-256 066da112e602cb32e0080758d6292191fe542a83b72689e983f1c5a0b74490e0

See more details on using hashes here.

File details

Details for the file flask_validators-0.2-py3-none-any.whl.

File metadata

File hashes

Hashes for flask_validators-0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 b7bcbdef8e451019322af91a026abfe73cee4457d0f287079dd71a054389d0a7
MD5 4df0b5d758c0097424bcbef32981d3db
BLAKE2b-256 d0f66b0b37706d75b9b83b6a2b52c45446ff8f505f9441f9aeb454aa080e52e7

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page