| 1 |
""" |
| 2 |
Caching framework. |
| 3 |
|
| 4 |
This package defines set of cache backends that all conform to a simple API. |
| 5 |
In a nutshell, a cache is a set of values -- which can be any object that |
| 6 |
may be pickled -- identified by string keys. For the complete API, see |
| 7 |
the abstract BaseCache class in django.core.cache.backends.base. |
| 8 |
|
| 9 |
Client code should use the `cache` variable defined here to access the default |
| 10 |
cache backend and look up non-default cache backends in the `caches` dict-like |
| 11 |
object. |
| 12 |
|
| 13 |
See docs/topics/cache.txt for information on the public API. |
| 14 |
""" |
| 15 |
|
| 16 |
from django.core import signals |
| 17 |
from django.core.cache.backends.base import ( |
| 18 |
BaseCache, |
| 19 |
CacheKeyWarning, |
| 20 |
InvalidCacheBackendError, |
| 21 |
InvalidCacheKey, |
| 22 |
) |
| 23 |
from django.utils.connection import BaseConnectionHandler, ConnectionProxy |
| 24 |
from django.utils.module_loading import import_string |
| 25 |
|
| 26 |
__all__ = [ |
| 27 |
"cache", |
| 28 |
"caches", |
| 29 |
"DEFAULT_CACHE_ALIAS", |
| 30 |
"InvalidCacheBackendError", |
| 31 |
"CacheKeyWarning", |
| 32 |
"BaseCache", |
| 33 |
"InvalidCacheKey", |
| 34 |
] |
| 35 |
|
| 36 |
DEFAULT_CACHE_ALIAS = "default" |
| 37 |
|
| 38 |
|
| 39 |
class CacheHandler(BaseConnectionHandler): |
| 40 |
settings_name = "CACHES" |
| 41 |
exception_class = InvalidCacheBackendError |
| 42 |
|
| 43 |
def create_connection(self, alias): |
| 44 |
params = self.settings[alias].copy() |
| 45 |
backend = params.pop("BACKEND") |
| 46 |
location = params.pop("LOCATION", "") |
| 47 |
try: |
| 48 |
backend_cls = import_string(backend) |
| 49 |
except ImportError as e: |
| 50 |
raise InvalidCacheBackendError( |
| 51 |
"Could not find backend '%s': %s" % (backend, e) |
| 52 |
) from e |
| 53 |
return backend_cls(location, params) |
| 54 |
|
| 55 |
|
| 56 |
caches = CacheHandler() |
| 57 |
|
| 58 |
cache = ConnectionProxy(caches, DEFAULT_CACHE_ALIAS) |
| 59 |
|
| 60 |
|
| 61 |
def close_caches(**kwargs): |
| 62 |
# Some caches need to do a cleanup at the end of a request cycle. If not |
| 63 |
# implemented in a particular backend cache.close() is a no-op. |
| 64 |
caches.close_all() |
| 65 |
|
| 66 |
|
| 67 |
signals.request_finished.connect(close_caches) |