Skip to content
Myr

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

3 files+164 added−0 removed

added:docs/patterns/caching.rst+69 added
1.. _caching-pattern:23Caching4=======56When your application runs slow, throw some caches in. Well, at least7it's the easiest way to speed up things. What does a cache do? Say you8have a function that takes some time to complete but the results would9still be good enough if they were 5 minutes old. So then the idea is that10you actually put the result of that calculation into a cache for some11time.1213Flask itself does not provide caching for you, but Werkzeug, one of the14libraries it is based on, has some very basic cache support. It supports15multiple cache backends, normally you want to use a memcached server.1617Setting up a Cache18------------------1920You create a cache object once and keep it around, similar to how21:class:`~flask.Flask` objects are created. If you are using the22development server you can create a23:class:`~werkzeug.contrib.cache.SimpleCache` object, that one is a simple24cache that keeps the item stored in the memory of the Python interpreter::2526 from werkzeug.contrib.cache import SimpleCache27 cache = SimpleCache()2829If you want to use memcached, make sure to have one of the memcache modules30supported (you get them from `PyPI <http://pypi.python.org/>`_) and a31memcached server running somewhere. This is how you connect to such an32memcached server then::3334 from werkzeug.contrib.cache import MemcachedCache35 cache = MemcachedCache(['127.0.0.1:11211'])3637If you are using appengine, you can connect to the appengine memcache38server easily::3940 from werkzeug.contrib.cache import GAEMemcachedCache41 cache = GAEMemcachedCache()4243Using a Cache44-------------4546Now how can one use such a cache? There are two very important47operations: :meth:`~werkzeug.contrib.cache.BaseCache.get` and 48:meth:`~werkzeug.contrib.cache.BaseCache.set`. This is how to use them:4950To get an item from the cache call51:meth:`~werkzeug.contrib.cache.BaseCache.get` with a string as key name.52If something is in the cache, it is returned. Otherwise that function53will return `None`::5455 rv = cache.get('my-item')5657To add items to the cache, use the :meth:`~werkzeug.contrib.cache.BaseCache.set`58method instead. The first argument is the key and the second the value59that should be set. Also a timeout can be provided after which the cache60will automatically remove item.6162Here a full example how this looks like normally::6364 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 rv
modified:docs/patterns/index.rst+2 added
15 unmodified lines
16 packages17 sqlite318 sqlalchemy19 fileuploads20 caching21 viewdecorators22 wtforms23 templateinheritance24 flashing25 jquery
added:docs/patterns/viewdecorators.rst+93 added
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 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, he 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 instanciated `cache` object is available, see93:ref:`caching-pattern` for more information.