Skip to content

Instantly share code, notes, and snippets.

@lqez
Created September 6, 2012 13:52
Show Gist options
  • Save lqez/3656474 to your computer and use it in GitHub Desktop.
Save lqez/3656474 to your computer and use it in GitHub Desktop.
a quick and dirty way to help dull django cache framework
from django.core.cache import cache
"""
a quick and dirty way to help dull django cache framework
Stores another copy of cache value with longer timeout value.
So, this will prevent multiple instances create a new copy of cache at same time.
Usage : Import this instead of 'django.core.cache'
and use your cache-related codes without any changes.
written by [email protected]
"""
suffix_for_backup = "__doublecached__"
suffix_for_lock = "__doublecache__lock__"
additional_timeout = 5 * 60 # 5 minutes
cache.original_get = cache.get
cache.original_set = cache.set
def get(key, default=None, version=None):
res = cache.original_get(key, default, version)
if res is None:
if cache.original_get(key+suffix_for_lock):
res = cache.original_get(key+suffix_for_backup, None, version)
else:
cache.original_set(key+suffix_for_lock, '1', additional_timeout)
return res
def set(key, value, timeout=None, version=None):
timeout_for_buffer = additional_timeout
if type(timeout) is int: timeout_for_buffer += timeout
cache.original_set(key+suffix_for_backup, value, timeout_for_buffer, version)
cache.delete(key+suffix_for_lock, version)
return cache.original_set(key, value, timeout, version)
cache.get = get
cache.set = set
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment