viewdecorators.rst
This file
Path
docs/patterns/viewdecorators.rst
171 lines · 6.2 KiB
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than 73739a2 point at it.
Merge branch '2.2.x'David Lordbefore adoption73739a2
lines 1–171why, one step back1View Decorators2===============34Python has a really interesting feature called function decorators. This5allows 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. 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 that19wraps and replaces another function. Since the original function is20replaced, you need to remember to copy the original function's information21to the new function. Use :func:`functools.wraps` to handle this for you.2223This example assumes that the login page is called ``'login'`` and that24the current user is stored in ``g.user`` and is ``None`` if there is no-one25logged in. ::2627 from functools import wraps28 from flask import g, request, redirect, url_for2930 def login_required(f):31 @wraps(f)32 def decorated_function(*args, **kwargs):33 if g.user is None:34 return redirect(url_for('login', next=request.url))35 return f(*args, **kwargs)36 return decorated_function3738To use the decorator, apply it as innermost decorator to a view function.39When applying further decorators, always remember40that the :meth:`~flask.Flask.route` decorator is the outermost. ::4142 @app.route('/secret_page')43 @login_required44 def secret_page():45 pass4647.. note::48 The ``next`` value will exist in ``request.args`` after a ``GET`` request for49 the login page. You'll have to pass it along when sending the ``POST`` request50 from the login form. You can do this with a hidden input tag, then retrieve it51 from ``request.form`` when logging the user in. ::5253 <input type="hidden" value="{{ request.args.get('next', '') }}"/>545556Caching Decorator57-----------------5859Imagine you have a view function that does an expensive calculation and60because of that you would like to cache the generated results for a61certain amount of time. A decorator would be nice for that. We're62assuming you have set up a cache like mentioned in :doc:`caching`.6364Here is an example cache function. It generates the cache key from a65specific prefix (actually a format string) and the current path of the66request. Notice that we are using a function that first creates the67decorator that then decorates the function. Sounds awful? Unfortunately68it is a little bit more complex, but the code should still be69straightforward to read.7071The decorated function will then work as follows72731. get the unique cache key for the current request based on the current74 path.752. get the value for that key from the cache. If the cache returned76 something we will return that value.773. otherwise the original function is called and the return value is78 stored in the cache for the timeout provided (by default 5 minutes).7980Here the code::8182 from functools import wraps83 from flask import request8485 def cached(timeout=5 * 60, key='view/{}'):86 def decorator(f):87 @wraps(f)88 def decorated_function(*args, **kwargs):89 cache_key = key.format(request.path)90 rv = cache.get(cache_key)91 if rv is not None:92 return rv93 rv = f(*args, **kwargs)94 cache.set(cache_key, rv, timeout=timeout)95 return rv96 return decorated_function97 return decorator9899Notice that this assumes an instantiated ``cache`` object is available, see100:doc:`caching`.101102103Templating Decorator104--------------------105106A common pattern invented by the TurboGears guys a while back is a107templating decorator. The idea of that decorator is that you return a108dictionary with the values passed to the template from the view function109and the template is automatically rendered. With that, the following110three examples do exactly the same::111112 @app.route('/')113 def index():114 return render_template('index.html', value=42)115116 @app.route('/')117 @templated('index.html')118 def index():119 return dict(value=42)120121 @app.route('/')122 @templated()123 def index():124 return dict(value=42)125126As you can see, if no template name is provided it will use the endpoint127of the URL map with dots converted to slashes + ``'.html'``. Otherwise128the provided template name is used. When the decorated function returns,129the dictionary returned is passed to the template rendering function. If130``None`` is returned, an empty dictionary is assumed, if something else than131a dictionary is returned we return it from the function unchanged. That132way you can still use the redirect function or return simple strings.133134Here is the code for that decorator::135136 from functools import wraps137 from flask import request, render_template138139 def templated(template=None):140 def decorator(f):141 @wraps(f)142 def decorated_function(*args, **kwargs):143 template_name = template144 if template_name is None:145 template_name = f"{request.endpoint.replace('.', '/')}.html"146 ctx = f(*args, **kwargs)147 if ctx is None:148 ctx = {}149 elif not isinstance(ctx, dict):150 return ctx151 return render_template(template_name, **ctx)152 return decorated_function153 return decorator154155156Endpoint Decorator157------------------158159When you want to use the werkzeug routing system for more flexibility you160need to map the endpoint as defined in the :class:`~werkzeug.routing.Rule`161to a view function. This is possible with this decorator. For example::162163 from flask import Flask164 from werkzeug.routing import Rule165166 app = Flask(__name__)167 app.url_map.add(Rule('/', endpoint='index'))168169 @app.endpoint('index')170 def my_index():171 return "Hello world"