Saved Bookmarks
| 1. |
How to decorate Views in Flask application? |
|
Answer» It makes little sense to decorate the view class itself because it is not the view FUNCTION that is introduced to the routing system. Instead, you'll have to hand-decorate the as_view() return value: def user_required(f):[Text Wrapping Break] """Checks whether USER is logged in or raises error 401."""[Text Wrapping Break] def decorator(*args, **kwargs):[Text Wrapping Break] if not g.user:[Text Wrapping Break] abort(401)[Text Wrapping Break] return f(*args, **kwargs)[Text Wrapping Break] return decorator[Text Wrapping Break][Text Wrapping Break]view = user_required(UserAPI.as_view('users'))[Text Wrapping Break]app.add_url_rule('/users/', view_func=view)Starting with FLASK 0.8, you can also specify a list of decorators to use in the class declaration: class UserAPI(MethodView):[Text Wrapping Break] decorators = [user_required]Keep in mind that you can't use conventional view decorators on the individual methods of the view because of the implicit SELF from the caller's perspective. |
|