This is an issue when decorators are applied directly to Flask View classes instead of using the decorators class attribute.
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:
@login_required won’t protect your endpoints 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.
Decorators applied directly to Flask view classes are silently ignored, which can lead to:
Move decorators from the class definition to the decorators class attribute. List them in the order they should be applied (innermost
decorator first).
@login_required
@cache(minutes=2)
class UserList(View):
def dispatch_request(self):
users = User.query.all()
return render_template('users.html', users=users) # Noncompliant
class UserList(View):
decorators = [cache(minutes=2), login_required]
def dispatch_request(self):
users = User.query.all()
return render_template('users.html', users=users)