Skip to content
Myr

Add simple decorator example

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Github issue #358

authored by Priit Laes · committed by Ron DuPlain · parent a59cbd4 · Browse files · 1 file+10 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+10 added−2 removed

  • other:+10 added−2 removed

1 file+10 added−2 removed

modified:docs/views.rst+10 added-2 removed
142 unmodified lines
143routing system it does not make much sense to decorate the class itself.144Instead you either have to decorate the return value of145:meth:`~flask.views.View.as_view` by hand::146147 def user_required(f):148 """Checks whether user is logged in or raises error 401."""149 def decorator(*args, **kwargs):150 if not g.user:151 abort(401)152 return f(*args, **kwargs)153 return decorator154147 view = rate_limited(UserAPI.as_view('users'))155 view = user_required(UserAPI.as_view('users'))156 app.add_url_rule('/users/', view_func=view)157158Starting with Flask 0.8 there is also an alternative way where you can159specify a list of decorators to apply in the class declaration::160161 class UserAPI(MethodView):154 decorators = [rate_limited]162 decorators = [user_required]163164Due to the implicit self from the caller's perspective you cannot use165regular view decorators on the individual methods of the view however,166keep this in mind.
71 unmodified lines