1 # -*- coding: utf-8 -*-
2 # This file is part of django-ssify, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See README.md for more information.
5 from __future__ import unicode_literals
7 from django.core.cache.backends.filebased import FileBasedCache
10 class StaticFileBasedCache(FileBasedCache):
11 def __init__(self, *args, **kwargs):
12 super(StaticFileBasedCache, self).__init__(*args, **kwargs)
13 self._dir = os.path.abspath(self._dir)
15 def make_key(self, key, version=None):
16 assert version is None, \
17 'StaticFileBasedCache does not support versioning.'
20 def _key_to_file(self, key):
21 key = os.path.abspath(os.path.join(self._dir, key.lstrip('/')))
22 assert key.startswith(self._dir), 'Trying to save path outside root.'
27 def get(self, key, default=None, version=None):
28 key = self.make_key(key, version=version)
29 self.validate_key(key)
30 fname = self._key_to_file(key)
32 with open(fname, 'rb') as inf:
34 except (IOError, OSError):
38 def set(self, key, value, timeout=None, version=None):
39 assert timeout is None, \
40 'StaticFileBasedCache does not support timeouts.'
41 key = self.make_key(key, version=version)
42 self.validate_key(key)
43 fname = self._key_to_file(key)
44 dirname = os.path.dirname(fname)
46 if not os.path.exists(dirname):
48 with open(fname, 'wb') as outf:
50 except (IOError, OSError):