viewdecorators.rst
This file
Path
docs/patterns/viewdecorators.rst
168 lines · 6.2 KiB
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than 7fc0ddb point at it.
Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption7fc0ddb
lines 1–168why, one step back1View 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 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 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.1415Login Required Decorator16------------------------1718So let's implement such a decorator. A decorator is a function that19returns a function. Pretty simple actually. The only thing you have to20keep in mind when implementing something like this is to update the21`__name__`, `__module__` and some other attributes of a function. This is22often forgotten, but you don't have to do that by hand, there is a23function for that that is used like a decorator (:func:`functools.wraps`).2425This example assumes that the login page is called ``'login'`` and that26the current user is stored as `g.user` and `None` if there is no-one27logged in::2829 from functools import wraps30 from flask import g, request, redirect, url_for3132 def login_required(f):33 @wraps(f)34 def decorated_function(*args, **kwargs):35 if g.user is None:36 return redirect(url_for('login', next=request.url))37 return f(*args, **kwargs)38 return decorated_function3940So how would you use that decorator now? Apply it as innermost decorator41to a view function. When applying further decorators, always remember42that the :meth:`~flask.Flask.route` decorator is the outermost::4344 @app.route('/secret_page')45 @login_required46 def secret_page():47 pass4849Caching Decorator50-----------------5152Imagine you have a view function that does an expensive calculation and53because 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 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 be62straightforward to read.6364The decorated function will then work as follows65661. get the unique cache key for the current request base on the current67 path.682. get the value for that key from the cache. If the cache returned69 something we will return that value.703. otherwise the original function is called and the return value is71 stored in the cache for the timeout provided (by default 5 minutes).7273Here the code::7475 from functools import wraps76 from flask import request7778 def cached(timeout=5 * 60, key='view/%s'):79 def decorator(f):80 @wraps(f)81 def decorated_function(*args, **kwargs):82 cache_key = key % request.path83 rv = cache.get(cache_key)84 if rv is not None:85 return rv86 rv = f(*args, **kwargs)87 cache.set(cache_key, rv, timeout=timeout)88 return rv89 return decorated_function90 return decorator9192Notice that this assumes an instantiated `cache` object is available, see93:ref:`caching-pattern` for more information.949596Templating Decorator97--------------------9899A common pattern invented by the TurboGears guys a while back is a100templating decorator. The idea of that decorator is that you return a101dictionary with the values passed to the template from the view function102and the template is automatically rendered. With that, the following103three examples do exactly the same::104105 @app.route('/')106 def index():107 return render_template('index.html', value=42)108109 @app.route('/')110 @templated('index.html')111 def index():112 return dict(value=42)113114 @app.route('/')115 @templated()116 def index():117 return dict(value=42)118119As you can see, if no template name is provided it will use the endpoint120of the URL map with dots converted to slashes + ``'.html'``. Otherwise121the provided template name is used. When the decorated function returns,122the dictionary returned is passed to the template rendering function. If123`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::128129 from functools import wraps130 from flask import request131132 def templated(template=None):133 def decorator(f):134 @wraps(f)135 def decorated_function(*args, **kwargs):136 template_name = template137 if template_name is None:138 template_name = request.endpoint \139 .replace('.', '/') + '.html'140 ctx = f(*args, **kwargs)141 if ctx is None:142 ctx = {}143 elif not isinstance(ctx, dict):144 return ctx145 return render_template(template_name, **ctx)146 return decorated_function147 return decorator148149150Endpoint Decorator151------------------152153When you want to use the werkzeug routing system for more flexibility you154need to map the endpoint as defined in the :class:`~werkzeug.routing.Rule` 155to a view function. This is possible with this decorator. For example:: 156157 from flask import Flask158 from werkzeug.routing import Rule159160 app = Flask(__name__) 161 app.url_map.add(Rule('/', endpoint='index')) 162163 @app.endpoint('index') 164 def my_index(): 165 return "Hello world" 166167168