| 1 |
from collections import defaultdict |
| 2 |
from threading import local |
| 3 |
|
| 4 |
from django.core.cache import caches |
| 5 |
from django.db import DEFAULT_DB_ALIAS |
| 6 |
|
| 7 |
from .settings import cachalot_settings |
| 8 |
from .signals import post_invalidation |
| 9 |
from .transaction import AtomicCache |
| 10 |
|
| 11 |
|
| 12 |
class CacheHandler(local): |
| 13 |
@property |
| 14 |
def atomic_caches(self): |
| 15 |
if not hasattr(self, '_atomic_caches'): |
| 16 |
self._atomic_caches = defaultdict(list) |
| 17 |
return self._atomic_caches |
| 18 |
|
| 19 |
def get_atomic_cache(self, cache_alias, db_alias, level): |
| 20 |
if cache_alias not in self.atomic_caches[db_alias][level]: |
| 21 |
self.atomic_caches[db_alias][level][cache_alias] = AtomicCache( |
| 22 |
self.get_cache(cache_alias, db_alias, level-1), db_alias) |
| 23 |
return self.atomic_caches[db_alias][level][cache_alias] |
| 24 |
|
| 25 |
def get_cache(self, cache_alias=None, db_alias=None, atomic_level=-1): |
| 26 |
if db_alias is None: |
| 27 |
db_alias = DEFAULT_DB_ALIAS |
| 28 |
if cache_alias is None: |
| 29 |
cache_alias = cachalot_settings.CACHALOT_CACHE |
| 30 |
|
| 31 |
min_level = -len(self.atomic_caches[db_alias]) |
| 32 |
if atomic_level < min_level: |
| 33 |
return caches[cache_alias] |
| 34 |
return self.get_atomic_cache(cache_alias, db_alias, atomic_level) |
| 35 |
|
| 36 |
def enter_atomic(self, db_alias): |
| 37 |
if db_alias is None: |
| 38 |
db_alias = DEFAULT_DB_ALIAS |
| 39 |
self.atomic_caches[db_alias].append({}) |
| 40 |
|
| 41 |
def exit_atomic(self, db_alias, commit): |
| 42 |
if db_alias is None: |
| 43 |
db_alias = DEFAULT_DB_ALIAS |
| 44 |
atomic_caches = self.atomic_caches[db_alias].pop().values() |
| 45 |
if commit: |
| 46 |
to_be_invalidated = set() |
| 47 |
for atomic_cache in atomic_caches: |
| 48 |
atomic_cache.commit() |
| 49 |
to_be_invalidated.update(atomic_cache.to_be_invalidated) |
| 50 |
# This happens when committing the outermost atomic block. |
| 51 |
if not self.atomic_caches[db_alias]: |
| 52 |
for table in to_be_invalidated: |
| 53 |
post_invalidation.send(table, db_alias=db_alias) |
| 54 |
|
| 55 |
|
| 56 |
cachalot_caches = CacheHandler() |