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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With