1 | "File-based cache backend"
|
---|
2 |
|
---|
3 | from django.core.cache.backends.simple import CacheClass as SimpleCacheClass
|
---|
4 | import os, time, urllib
|
---|
5 | try:
|
---|
6 | import cPickle as pickle
|
---|
7 | except ImportError:
|
---|
8 | import pickle
|
---|
9 |
|
---|
10 | class CacheClass(SimpleCacheClass):
|
---|
11 | def __init__(self, dir, params):
|
---|
12 | self._dir = dir
|
---|
13 | if not os.path.exists(self._dir):
|
---|
14 | self._createdir()
|
---|
15 | SimpleCacheClass.__init__(self, dir, params)
|
---|
16 | del self._cache
|
---|
17 | del self._expire_info
|
---|
18 |
|
---|
19 | def get(self, key, default=None):
|
---|
20 | fname = self._key_to_file(key)
|
---|
21 | try:
|
---|
22 | f = open(fname, 'rb')
|
---|
23 | exp = pickle.load(f)
|
---|
24 | now = time.time()
|
---|
25 | if exp < now:
|
---|
26 | f.close()
|
---|
27 | os.remove(fname)
|
---|
28 | else:
|
---|
29 | return pickle.load(f)
|
---|
30 | except (IOError, OSError, EOFError, pickle.PickleError):
|
---|
31 | pass
|
---|
32 | return default
|
---|
33 |
|
---|
34 | def set(self, key, value, timeout=None):
|
---|
35 | fname = self._key_to_file(key)
|
---|
36 | if timeout is None:
|
---|
37 | timeout = self.default_timeout
|
---|
38 |
|
---|
39 | namespacedir = os.path.dirname(fname)
|
---|
40 | try:
|
---|
41 | filelist = os.listdir(namespacedir)
|
---|
42 | except (IOError, OSError):
|
---|
43 | self._createdir(namespacedir)
|
---|
44 | filelist = []
|
---|
45 | if len(filelist) > self._max_entries:
|
---|
46 | self._cull(filelist)
|
---|
47 |
|
---|
48 | try:
|
---|
49 | f = open(fname, 'wb')
|
---|
50 | now = time.time()
|
---|
51 | pickle.dump(now + timeout, f, 2)
|
---|
52 | pickle.dump(value, f, 2)
|
---|
53 | except (IOError, OSError):
|
---|
54 | pass
|
---|
55 |
|
---|
56 | def delete(self, key):
|
---|
57 | try:
|
---|
58 | os.remove(self._key_to_file(key))
|
---|
59 | except (IOError, OSError):
|
---|
60 | pass
|
---|
61 |
|
---|
62 | def has_key(self, key):
|
---|
63 | return os.path.exists(self._key_to_file(key))
|
---|
64 |
|
---|
65 | def _cull(self, filelist):
|
---|
66 | if self._cull_frequency == 0:
|
---|
67 | doomed = filelist
|
---|
68 | else:
|
---|
69 | doomed = [k for (i, k) in enumerate(filelist) if i % self._cull_frequency == 0]
|
---|
70 | for fname in doomed:
|
---|
71 | try:
|
---|
72 | os.remove(os.path.join(self._dir, fname))
|
---|
73 | except (IOError, OSError):
|
---|
74 | pass
|
---|
75 |
|
---|
76 | def _createdir(self, dir = None):
|
---|
77 | if dir == None:
|
---|
78 | dir = self._dir
|
---|
79 | try:
|
---|
80 | os.makedirs(dir)
|
---|
81 | except OSError:
|
---|
82 | raise EnvironmentError, "Cache directory '%s' does not exist and could not be created'" % self._dir
|
---|
83 |
|
---|
84 | def _key_to_file(self, key):
|
---|
85 | return os.path.join(self._dir, (key))
|
---|