Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorate methods in derived classes of Flask MethodView

I thought that I would be able to require login for all derived views by decorating __enter__ as follows:

from flask.views import MethodView
from flask.ext.login import login_required
class LoggedInView(MethodView):
    @login_required
    def __enter__(self):
        pass

If I add some logging, it turns out __enter__ is not entered. Similarly, __exit__ doesn't happen.

What's going on here?

I can modify the style to decorate some other function, but then it's necessary to call super() in derived views which defeats the point of doing this to begin with.

How can I enforce this decoration without any work in views beyond inheriting LoggedInView?

like image 485
OJFord Avatar asked Jan 25 '26 17:01

OJFord


1 Answers

To decorate the methods of a MethodView instance you have to add a decorators class variable with the list of decorators to call. See the documentation.

For your example, it would be:

from flask.views import MethodView
from flask.ext.login import login_required

class LoggedInView(MethodView):
    decorators = [login_required]

    def get(self):
        pass

    def post(self):
        pass

    # ...

Note that the decorators are applied to all the methods that are defined.

like image 129
Miguel Avatar answered Jan 28 '26 08:01

Miguel