1. Decorators

"It will help us on validating json request, request param"

https://chatgpt.com/share/9b52ffe2-07f2-441c-b269-b9f5f1c989d5

In Flask, decorators are a powerful and elegant way to modify the behavior of functions or classes. They are used extensively in Flask to handle routing, request processing, and other aspects of web application behavior. Here's a more detailed explanation:

What are Decorators?

In Python, a decorator is a function that wraps another function or method, modifying or extending its behavior. Decorators are denoted with the @ symbol above the function definition. Here's a simple example:

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

Output:

Something is happening before the function is called.
Hello!
Something is happening after the function is called.

Decorators in Flask

Flask uses decorators extensively to simplify the process of setting up routes, handling requests, and managing other aspects of the application.

1. Route Decorators

The most common use of decorators in Flask is for routing. The @app.route decorator is used to bind a URL to a view function:

In this example, @app.route('/') binds the URL / to the home function, and @app.route('/about') binds the URL /about to the about function.

2. HTTP Method Decorators

Flask allows specifying which HTTP methods a view function should respond to using decorators like @app.route with the methods argument:

3. Custom Decorators

You can also create your own decorators to add custom behavior to your view functions. For example, you might create a decorator to check if a user is authenticated before allowing access to a view:

In this example, the login_required decorator checks if the user is logged in by inspecting cookies. If the user is not logged in, it redirects to the login page. Otherwise, it proceeds with the original view function.

Summary

Decorators in Flask provide a clean and readable way to add functionality to your view functions. By understanding and using decorators, you can create more modular, reusable, and maintainable code in your Flask applications.

Last updated