This is an issue when decorators are applied directly to Flask View classes instead of using the decorators class attribute.

Why is this an issue?

In Flask, class-based views work differently from regular view functions. When you create a class-based view, the actual view function is generated by calling the as_view() method.

Decorators applied directly to the view class are not applied to this generated view function. This means your decorators will have no effect - they won’t be executed when requests are handled.

This can lead to serious problems:

Flask provides the decorators class attribute specifically to handle this. When you list decorators in this attribute, Flask applies them to the view function returned by as_view(), ensuring they work correctly.

What is the potential impact?

Decorators applied directly to Flask view classes are silently ignored, which can lead to:

How to fix it

Move decorators from the class definition to the decorators class attribute. List them in the order they should be applied (innermost decorator first).

Code examples

Noncompliant code example

@login_required
@cache(minutes=2)
class UserList(View):
    def dispatch_request(self):
        users = User.query.all()
        return render_template('users.html', users=users)  # Noncompliant

Compliant solution

class UserList(View):
    decorators = [cache(minutes=2), login_required]

    def dispatch_request(self):
        users = User.query.all()
        return render_template('users.html', users=users)

Resources

Documentation