Install the extension with one of the following commands:
$ easy_install Flask-Cache
or alternatively if you have pip installed:
$ pip install Flask-Cache
The following configuration values exist for Flask-Cache:
| CACHE_TYPE | Specifies which type of caching object to use. This is an import string that will be imported and instantiated. It is assumed that the import object is a function that will return a cache object that adheres to the werkzeug cache API. For werkzeug.contrib.cache objects, you do not need to specify the entire import string, just one of the following names. Built-in cache types:
|
| CACHE_ARGS | Optional list to unpack and pass during the cache class instantiation. |
| CACHE_OPTIONS | Optional dictionary to pass during the cache class instantiation. |
| CACHE_DEFAULT_TIMEOUT | The default timeout that is used if no timeout is specified. Unit of time is seconds. |
| CACHE_THRESHOLD | The maximum number of items the cache will store before it starts deleting some. Used only for SimpleCache and FileSystemCache |
| CACHE_KEY_PREFIX | A prefix that is added before all keys. This makes it possible to use the same memcached server for different apps. Used only for MemcachedCache and GAEMemcachedCache. |
| CACHE_MEMCACHED_SERVERS | A list or a tuple of server addresses. Used only for MemcachedCache |
| CACHE_REDIS_HOST | A Redis server host. Used only for RedisCache. |
| CACHE_REDIS_PORT | A Redis server port. Default is 6379. Used only for RedisCache. |
| CACHE_DIR | Directory to store cache. Used only for FileSystemCache. |
In addition the standard Flask TESTING configuration option is used. If this is True then Flask-Cache will use NullCache only.
Cache is managed through a Cache instance:
from flask import Flask
from flaskext.cache import Cache
app = Flask(__name__)
cache = Cache(app)
You may also set up your Cache instance later at configuration time using init_app method:
cache = Cache()
app = Flask(__name__)
cache.init_app(app)
To cache view functions you will use the cached() decorator. This decorator will use request.path by default for the cache_key.:
@cache.cached(timeout=50)
def index():
return render_template('index.html')
The cached decorator has another optional argument called unless. This argument accepts a callable that returns True or False. If unless returns True then it will bypass the caching mechanism entirely.
Using the same @cached decorator you are able to cache the result of other non-view related functions. The only stipulation is that you replace the key_prefix, otherwise it will use the request.path cache_key.:
@cache.cached(timeout=50, key_prefix='all_comments')
def get_all_comments():
comments = do_serious_dbio()
return [x.author for x in comments]
cached_comments = get_all_comments()
See memoize()
In memoization, the functions arguments are also included into the cache_key.
Memoize is also designed for instance objects, since it will take into account that functions id. The theory here is that if you have a function you need to call several times in one request, it would only be calculated the first time that function is called with those arguments. For example, an sqlalchemy object that determines if a user has a role. You might need to call this function many times during a single request.:
User(db.Model):
@cache.memoize(50)
def has_membership(role):
return self.groups.filter_by(role=role).count() >= 1
New in version 0.2.
You might need to delete the cache on a per-function bases. Using the above example, lets say you change the users permissions and assign them to a role, but now you need to re-calculate if they have certain memberships or not. You can do this with the delete_memoized() function.:
cache.delete_memoized('has_membership')
Note
If only the function name is given as parameter, all the memoized versions of it will be erazed. However, you can delete specific cache by providing the same parameter values as when caching. In following example only the user -roled cache is erased:
has_membership('admin')
has_membership('user')
cache.delete_memoized('has_membership', 'user')
You are able to easily add your own custom cache backends by exposing a function that can instantiate and return a cache object. CACHE_TYPE will be the import string to your custom function. It should expect to receive three arguments.
Your custom cache object must also subclass the werkzeug.contrib.cache.BaseCache class. Flask-Cache will make sure that threshold is already included in the kwargs options dictionary since it is common to all BaseCache classes.
An example Redis cache implementation:
#: the_app/custom.py
class RedisCache(BaseCache):
def __init__(self, servers, default_timeout=500):
pass
def redis(app, args, kwargs):
args.append(app.config['REDIS_SERVERS'])
return RedisCache(*args, **kwargs)
With this example, your CACHE_TYPE might be the_app.custom.redis
This class is used to control the cache objects.
If TESTING is True it will use NullCache.
Proxy function for internal cache object.
Proxy function for internal cache object.
Proxy function for internal cache object.
Proxy function for internal cache object.
Decorator. Use this to cache a function. By default the cache key is view/request.path. You are able to use this decorator with any function by changing the key_prefix. If the token %s is located within the key_prefix then it will replace that with request.path
Example:
# An example view function
@cache.cached(timeout=50)
def big_foo():
return big_bar_calc()
# An example misc function to cache.
@cache.cached(key_prefix='MyCachedList')
def get_list():
return [random.randrange(0, 1) for i in range(50000)]
my_list = get_list()
Note
You MUST have a request context to actually called any functions that are cached.
New in version 0.4: The returned decorated function now has three function attributes assigned to it. These attributes are readable/writable.
- uncached
- The original undecorated function
- cache_timeout
- The cache timeout value for this function. For a custom value to take affect, this must be set before the function is called.
- make_cache_key
- A function used in generating the cache_key used.
| Parameters: |
|
|---|
Use this to cache the result of a function, taking its arguments into account in the cache key.
Information on Memoization.
Example:
@cache.memoize(timeout=50)
def big_foo(a, b):
return a + b + random.randrange(0, 1000)
>>> big_foo(5, 2)
753
>>> big_foo(5, 3)
234
>>> big_foo(5, 2)
753
New in version 0.4: The returned decorated function now has three function attributes assigned to it. These attributes are readable/writable.
- uncached
- The original undecorated function
- cache_timeout
- The cache timeout value for this function. For a custom value to take affect, this must be set before the function is called.
- make_cache_key
- A function used in generating the cache_key used.
| Parameters: | timeout – Default None. If set to an integer, will cache for that amount of time. Unit of time is in seconds. |
|---|
Deletes the specified functions caches, based by given parameters. If parameters are given, only the functions that were memoized with them will be erased. Otherwise all the versions of the caches will be deleted.
Example:
@cache.memoize(50)
def random_func():
return random.randrange(1, 50)
@cache.memoize()
def param_func(a, b):
return a+b+random.randrange(1, 50)
>>> random_func()
43
>>> random_func()
43
>>> cache.delete_memoized('random_func')
>>> random_func()
16
>>> param_func(1, 2)
32
>>> param_func(1, 2)
32
>>> param_func(2, 2)
47
>>> cache.delete_memoized('param_func', 1, 2)
>>> param_func(1, 2)
13
>>> param_func(2, 2)
47
| Parameters: |
|
|---|
Returns all function names used for memoized functions.
This will include multiple function names when the memoized function has been called with differing arguments.
| Returns: | set of function names |
|---|
Returns all cache_keys used for memoized functions.
| Returns: | list generator of cache_keys |
|---|
Uses base64 for memoize caching. This fixes rare issues where the cache_key was either a tuple or larger than the caching backend would be able to support.
Adds support for deleting memoized caches optionally based on function parameters.
Python 2.5 compatibility, plus bugfix with string.format.
Added the ability to retrieve memoized function names or cache keys.
Bugfix release. Fixes a bug that would cause an exception if no CACHE_TYPE was supplied.
Pypi egg fix.