Just two helper functions to manage cache witch is using file base dependent data.from django.core.cache import cacheimport sha, osFILE_CACHE_TIMEOUT = 60 * 60 * 60 * 24 * 31 # 1 monthFILE_CACHE_FMT = '%(name)s_%(hash)s'def set_cached_file(path, value): """ Store file dependent data in cache. Timeout is set to FILE_CACHE_TIMEOUT (1month). Key is created from base name of file and SHA1 digest of the path. """ mtime = os.path.getmtime(path) sh = sha.new() sh.update(path) hash = sh.hexdigest() name = os.path.basename(path) cache.set(FILE_CACHE_FMT % locals(), (mtime, value,), FILE_CACHE_TIMEOUT)#def get_cached_file(path, default=None): """ Get file content from cache. If modification time differ return None and delete data from cache. """ sh = sha.new() sh.update(path) hash = sh.hexdigest() name = os.path.basename(path) key = FILE_CACHE_FMT % locals() cached = cache.get(key, default) if cached is None: return None mtime, value = cached if (not os.path.isfile(path)) or (os.path.getmtime(path) != mtime): # file is changed or deleted cache.delete(key) # delete from cache return None else: return value#
|