7f421458d0dabf7fca02d785c2523d28eaeb9f22
[django-ssify.git] / ssify / cache.py
1 import os
2 from django.core.cache.backends.filebased import FileBasedCache
3
4
5 class StaticFileBasedCache(FileBasedCache):
6     def __init__(self, *args, **kwargs):
7         super(StaticFileBasedCache, self).__init__(*args, **kwargs)
8         self._dir = os.path.abspath(self._dir)
9
10     def make_key(self, key, version=None):
11         assert version is None, \
12             'StaticFileBasedCache does not support versioning.'
13         return key
14
15     def _key_to_file(self, key):
16         key = os.path.abspath(os.path.join(self._dir, key.lstrip('/')))
17         assert key.startswith(self._dir), 'Trying to save path outside root.'
18         if key.endswith('/'):
19             key += 'index.html'
20         return key
21
22     def get(self, key, default=None, version=None):
23         key = self.make_key(key, version=version)
24         self.validate_key(key)
25         fname = self._key_to_file(key)
26         try:
27             with open(fname, 'rb') as inf:
28                 return inf.read()
29         except (IOError, OSError):
30             pass
31         return default
32
33     def set(self, key, value, timeout=None, version=None):
34         assert timeout is None, \
35             'StaticFileBasedCache does not support timeouts.'
36         key = self.make_key(key, version=version)
37         self.validate_key(key)
38         fname = self._key_to_file(key)
39         dirname = os.path.dirname(fname)
40         try:
41             if not os.path.exists(dirname):
42                 os.makedirs(dirname)
43             with open(fname, 'wb') as outf:
44                 outf.write(value)
45         except (IOError, OSError):
46             pass