Skip to content
Myr

Merge pull request #1010 from plumdog/master

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

Tweaks to docs/patterns/viewdecorators.rst

authored by Kenneth Reitz · committed by Kenneth Reitz · parents fa6eded, b2b531a · Browse files · 1 file+6 added−9 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+6 added−9 removed

  • other:+6 added−9 removed

1 file+6 added−9 removed

modified:docs/patterns/viewdecorators.rst+6 added-9 removed
1View Decorators2===============34Python has a really interesting feature called function decorators. This5allow some really neat things for web applications. Because each view in6Flask is a function decorators can be used to inject additional5allows some really neat things for web applications. Because each view in6Flask is a function, decorators can be used to inject additional7functionality to one or more functions. The :meth:`~flask.Flask.route`8decorator is the one you probably used already. But there are use cases9for implementing your own decorator. For instance, imagine you have a10view that should only be used by people that are logged in to. If a user10view that should only be used by people that are logged in. If a user11goes to the site and is not logged in, they should be redirected to the12login page. This is a good example of a use case where a decorator is an13excellent solution.14
38 unmodified lines
53because of that you would like to cache the generated results for a54certain amount of time. A decorator would be nice for that. We're55assuming you have set up a cache like mentioned in :ref:`caching-pattern`.5657Here an example cache function. It generates the cache key from a57Here is an example cache function. It generates the cache key from a58specific prefix (actually a format string) and the current path of the59request. Notice that we are using a function that first creates the60decorator that then decorates the function. Sounds awful? Unfortunately61it is a little bit more complex, but the code should still be
61 unmodified lines
123`None` is returned, an empty dictionary is assumed, if something else than124a dictionary is returned we return it from the function unchanged. That125way you can still use the redirect function or return simple strings.126127Here the code for that decorator::127Here is the code for that decorator::128129 from functools import wraps130 from flask import request130 from flask import request, render_template131132 def templated(template=None):133 def decorator(f):134 @wraps(f)
27 unmodified lines
162163 @app.endpoint('index') 164 def my_index(): 165 return "Hello world" 166167168