Merge branch 'master' into module-support
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parents 41de129, 4559e4f · Browse files · 3 files·+164 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+164 added−0 removed
- other:+164 added−0 removed
Provenance
- Commit
13933ee- Tree
0647fd9- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent 1
41de129- Parent 2
4559e4f
3 files changed+164 added−0 removed
added:docs/patterns/caching.rst+69 added
1+.. _caching-pattern:2+3+Caching4+=======5+6+When your application runs slow, throw some caches in. Well, at least7+it's the easiest way to speed up things. What does a cache do? Say you8+have a function that takes some time to complete but the results would9+still be good enough if they were 5 minutes old. So then the idea is that10+you actually put the result of that calculation into a cache for some11+time.12+13+Flask itself does not provide caching for you, but Werkzeug, one of the14+libraries it is based on, has some very basic cache support. It supports15+multiple cache backends, normally you want to use a memcached server.16+17+Setting up a Cache18+------------------19+20+You create a cache object once and keep it around, similar to how21+:class:`~flask.Flask` objects are created. If you are using the22+development server you can create a23+:class:`~werkzeug.contrib.cache.SimpleCache` object, that one is a simple24+cache that keeps the item stored in the memory of the Python interpreter::25+26+ from werkzeug.contrib.cache import SimpleCache27+ cache = SimpleCache()28+29+If you want to use memcached, make sure to have one of the memcache modules30+supported (you get them from `PyPI <http://pypi.python.org/>`_) and a31+memcached server running somewhere. This is how you connect to such an32+memcached server then::33+34+ from werkzeug.contrib.cache import MemcachedCache35+ cache = MemcachedCache(['127.0.0.1:11211'])36+37+If you are using appengine, you can connect to the appengine memcache38+server easily::39+40+ from werkzeug.contrib.cache import GAEMemcachedCache41+ cache = GAEMemcachedCache()42+43+Using a Cache44+-------------45+46+Now how can one use such a cache? There are two very important47+operations: :meth:`~werkzeug.contrib.cache.BaseCache.get` and 48+:meth:`~werkzeug.contrib.cache.BaseCache.set`. This is how to use them:49+50+To get an item from the cache call51+:meth:`~werkzeug.contrib.cache.BaseCache.get` with a string as key name.52+If something is in the cache, it is returned. Otherwise that function53+will return `None`::54+55+ rv = cache.get('my-item')56+57+To add items to the cache, use the :meth:`~werkzeug.contrib.cache.BaseCache.set`58+method instead. The first argument is the key and the second the value59+that should be set. Also a timeout can be provided after which the cache60+will automatically remove item.61+62+Here a full example how this looks like normally::63+64+ def get_my_item():65+ rv = cache.get('my-item')66+ if rv is None:67+ rv = calculate_value()68+ cache.set('my-item', rv, timeout=5 * 60)69+ return rvmodified:docs/patterns/index.rst+2 added
15 unmodified lines16 packages17 sqlite318 sqlalchemy19 fileuploads20+ caching21+ viewdecorators22 wtforms23 templateinheritance24 flashing25 jqueryadded:docs/patterns/viewdecorators.rst+93 added
1+View Decorators2+===============3+4+Python has a really interesting feature called function decorators. This5+allow some really neat things for web applications. Because each view in6+Flask is a function decorators can be used to inject additional7+functionality to one or more functions. The :meth:`~flask.Flask.route`8+decorator is the one you probably used already. But there are use cases9+for implementing your own decorator. For instance, imagine you have a10+view that should only be used by people that are logged in to. If a user11+goes to the site and is not logged in, he should be redirected to the12+login page. This is a good example of a use case where a decorator is an13+excellent solution.14+15+Login Required Decorator16+------------------------17+18+So let's implement such a decorator. A decorator is a function that19+returns a function. Pretty simple actually. The only thing you have to20+keep in mind when implementing something like this is to update the21+`__name__`, `__module__` and some other attributes of a function. This is22+often forgotten, but you don't have to do that by hand, there is a23+function for that that is used like a decorator (:func:`functools.wraps`).24+25+This example assumes that the login page is called ``'login'`` and that26+the current user is stored as `g.user` and `None` if there is no-one27+logged in::28+29+ from functools import wraps30+ from flask import g, request, redirect, url_for31+32+ 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_function39+40+So how would you use that decorator now? Apply it as innermost decorator41+to a view function. When applying further decorators, always remember42+that the :meth:`~flask.Flask.route` decorator is the outermost::43+44+ @app.route('/secret_page')45+ @login_required46+ def secret_page():47+ pass48+49+Caching Decorator50+-----------------51+52+Imagine you have a view function that does an expensive calculation and53+because of that you would like to cache the generated results for a54+certain amount of time. A decorator would be nice for that. We're55+assuming you have set up a cache like mentioned in :ref:`caching-pattern`.56+57+Here an example cache function. It generates the cache key from a58+specific prefix (actually a format string) and the current path of the59+request. Notice that we are using a function that first creates the60+decorator that then decorates the function. Sounds awful? Unfortunately61+it is a little bit more complex, but the code should still be62+straightforward to read.63+64+The decorated function will then work as follows65+66+1. get the unique cache key for the current request base on the current67+ path.68+2. get the value for that key from the cache. If the cache returned69+ something we will return that value.70+3. otherwise the original function is called and the return value is71+ stored in the cache for the timeout provided (by default 5 minutes).72+73+Here the code::74+75+ from functools import wraps76+ from flask import request77+78+ 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 decorator91+92+Notice that this assumes an instanciated `cache` object is available, see93+:ref:`caching-pattern` for more information.