v. 0.2.4:
[django-ssify.git] / ssify / cache_backends.py
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.
4 #
5 from __future__ import unicode_literals
6 import os
7 from django.core.cache.backends.filebased import FileBasedCache
8
9
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)
14
15     def make_key(self, key, version=None):
16         assert version is None, \
17             'StaticFileBasedCache does not support versioning.'
18         return key
19
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.'
23         if key.endswith('/'):
24             key += 'index.html'
25         return key
26
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)
31         try:
32             with open(fname, 'rb') as inf:
33                 return inf.read()
34         except (IOError, OSError):
35             pass
36         return default
37
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)
45         try:
46             if not os.path.exists(dirname):
47                 os.makedirs(dirname)
48             with open(fname, 'wb') as outf:
49                 outf.write(value)
50         except (IOError, OSError):
51             pass