Created
August 12, 2011 08:37
-
-
Save j4mie/1141706 to your computer and use it in GitHub Desktop.
Proof-of-concept JSON-based Django cache backend for offline operation of django_compressor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from django.core.cache.backends.base import BaseCache | |
from django.utils import simplejson as json | |
from django.conf import settings as django_settings | |
from compressor.conf import settings | |
class CompressorManifestCache(BaseCache): | |
"""Proof of concept, do not use""" | |
def __init__(self, host, *args, **kwargs): | |
self._prepare() | |
super(CompressorManifestCache, self).__init__(*args, **kwargs) | |
def get(self, key, default=None, version=None): | |
key = self.make_key(key, version=version) | |
val = self._cache.get(key) | |
if val is None: | |
return default | |
return val | |
def set(self, key, value, timeout=0, version=None): | |
key = self.make_key(key, version=version) | |
self._cache[key] = value | |
# Shouldn't have to do this on every `set` call, but | |
# `close()` is only called by the request_finished | |
# signal, so doesn't work in a management command. | |
self._dump() | |
def _dump(self): | |
file = open(self._get_filepath(), 'w') | |
json.dump(self._cache, file) | |
file.close() | |
def _get_dir(self): | |
return os.path.join( | |
django_settings.STATIC_ROOT, | |
settings.COMPRESS_OUTPUT_DIR.strip('/') | |
) | |
def _get_filepath(self): | |
return os.path.join(self._get_dir(), 'manifest.json') | |
def _create_dirs(self): | |
if not os.path.exists(self._get_dir()): | |
os.makedirs(self._get_dir()) | |
def _prepare(self): | |
self._create_dirs() | |
try: | |
file = open(self._get_filepath()) | |
self._cache = json.load(file) | |
file.close() | |
except IOError: | |
self._cache = {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CACHES['compressor'] = { | |
'BACKEND': 'path.to.CompressorManifestCache', | |
} | |
COMPRESS_ENABLED = True | |
COMPRESS_OFFLINE = True | |
COMPRESS_CACHE_BACKEND = 'compressor' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment