| 1 |
.. _custom-cache-backends: |
| 2 |
|
| 3 |
Custom Cache Backends |
| 4 |
--------------------- |
| 5 |
|
| 6 |
You are able to easily add your own custom cache backends by exposing a |
| 7 |
function that can instantiate and return a cache object. ``CACHE_TYPE`` will be |
| 8 |
the import string to your custom cache type. If not a subclass of |
| 9 |
:class:`.BaseCache`, Flask-Caching will call it |
| 10 |
with three arguments: |
| 11 |
|
| 12 |
* ``app``, the Flask application object the cache is being initialized for |
| 13 |
* ``args``, the value of the CACHE_ARGS configuration option |
| 14 |
* ``kwargs``, the value of the CACHE_OPTIONS configuration option |
| 15 |
|
| 16 |
.. note:: ``args`` and ``kwargs`` are not expanded when instantiating the cache |
| 17 |
object, i.e. they are not passed in as ``*args`` and ``**kwargs``, but they |
| 18 |
are the exact value of the CACHE_ARGS and CACHE_OPTIONS configuration |
| 19 |
options (CACHE_ARGS, however, is converted to a list). |
| 20 |
|
| 21 |
Your custom cache should, however, subclass the |
| 22 |
:class:`.BaseCache` class so it provides all the |
| 23 |
necessary methods to be usable. |
| 24 |
|
| 25 |
.. versionchanged:: 1.9.1 If your custom cache type *is* a subclass of |
| 26 |
:class:`.BaseCache`, Flask-Caching will, instead |
| 27 |
of directly instantiating the class, call its ``factory`` class method with |
| 28 |
the same args as listed above. Unless overridden, ``BaseCache.factory`` |
| 29 |
simply instantiates the object without passing any arguments to it. |
| 30 |
Built-in cache classes have overridden this to mimic the old, function based |
| 31 |
cache isntantiation, so if you subclassed something that is not |
| 32 |
:class:`.BaseCache`, you may want to consult the |
| 33 |
source code to see if your class is still compatible. |
| 34 |
|
| 35 |
An example implementation:: |
| 36 |
|
| 37 |
#: the_app/custom.py |
| 38 |
class RedisCache(BaseCache): |
| 39 |
def __init__(self, servers, default_timeout=500): |
| 40 |
pass |
| 41 |
|
| 42 |
@classmethod |
| 43 |
def factory(cls, app, args, kwargs): |
| 44 |
args.append(app.config['REDIS_SERVERS']) |
| 45 |
|
| 46 |
return cls(*args, **kwargs) |
| 47 |
|
| 48 |
With this example, your ``CACHE_TYPE`` might be ``the_app.custom.RedisCache`` |
| 49 |
|
| 50 |
CACHE_TYPE doesn’t have to directly point to a cache class, though. An example |
| 51 |
PylibMC cache implementation to change binary setting and provide |
| 52 |
username/password if SASL is enabled on the library:: |
| 53 |
|
| 54 |
#: the_app/custom.py |
| 55 |
def pylibmccache(app, config, args, kwargs): |
| 56 |
return pylibmc.Client(servers=config['CACHE_MEMCACHED_SERVERS'], |
| 57 |
username=config['CACHE_MEMCACHED_USERNAME'], |
| 58 |
password=config['CACHE_MEMCACHED_PASSWORD'], |
| 59 |
binary=True) |
| 60 |
|
| 61 |
With this example, your ``CACHE_TYPE`` might be ``the_app.custom.pylibmccache`` |