-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.py
309 lines (247 loc) · 9.3 KB
/
cache.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import cPickle
import functools
import logging
from time import time as sys_time
from tornado.options import options
__all__ = ['cached', 'autocache']
class _Cache(object):
"""python-memcahe compatable instance cache
"""
def __init__(self):
self._app_cache = {}
@classmethod
def create_memcache(cls):
if hasattr(cls, '_memcache'):
return cls._memcache
if hasattr(options, 'memcache_clients') and options.memcache_clients:
try:
import pylibmc
cache = pylibmc.Client(options.memcache_clients,
**options.memcache_kwargs)
cls._memcache = cache
return cls._memcache
except ImportError:
import memcache
cache = memcache.Client(options.memcache_clients,
**options.memcache_kwargs)
cls._memcache = cache
return cls._memcache
except ImportError:
cls._memcache = cls()
return cls._memcache
else:
cls._memcache = cls()
return cls._memcache
@classmethod
def create_redis(cls):
if hasattr(cls, '_redis'):
return cls._redis
if hasattr(options, 'redis_clients') and options.redis_clients:
try:
import redis
pool = redis.ConnectionPool(host=options.redis_clients['host'], port=options.redis_clients['port'])
client = redis.Redis(connection_pool=pool)
cls._redis = client
print "import redis.py, create default redis from "+ options.redis_clients['host']
return cls._redis
except ImportError as e:
print "import error, create default redis member cache"
raise e
# cls._redis = cls()
# return cls._redis
else:
print "has no redis client options, create default redis member cache"
cls._redis = cls()
return cls._redis
def flush_all(self):
self._app_cache = {}
def set(self, key, val, time=0):
key = str(key)
if time < 0:
time = 0
self._app_cache[key] = (val, sys_time(), time)
return val
def get(self, key):
key = str(key)
_store = self._app_cache.get(key, None)
if not _store:
return None
value, begin, seconds = _store
if seconds and sys_time() > begin + seconds:
del self._app_cache[key]
return None
return value
def add(self, key, val, time=0):
key = str(key)
if key not in self._app_cache:
return self.set(key, val, time)
return self.get(key)
def delete(self, key, time=0):
key = str(key)
if key in self._app_cache:
del self._app_cache[key]
return None
def incr(self, key, delta=1):
key = str(key)
_store = self._app_cache.get(key, None)
if not _store:
return None
value, begin, seconds = _store
if seconds and sys_time() > begin + seconds:
del self._app_cache[key]
return None
if isinstance(value, basestring):
value = int(value)
value = value + delta
self.set(key, value)
return value
def decr(self, key, delta=1):
return self.incr(key, -delta)
def set_multi(self, mapping, time=0, key_prefix=''):
for key, value in mapping.items():
self.set('%s%s' % (key_prefix, key), value, time)
return True
def get_multi(self, keys, key_prefix=''):
dct = {}
for key in keys:
value = self.get('%s%s' % (key_prefix, key))
if value:
dct[key] = value
return dct
def delete_multi(self, keys, time=0, key_prefix=''):
for key in keys:
self.delete('%s%s' % (key_prefix, key))
return None
simple_cache = _Cache.create_memcache()
complex_cache =_Cache.create_redis()
redis_cache = complex_cache
class cached(object):
"""Cache decorator, an easy way to manage cache.
The result key will be like: prefix:arg1-arg2
"""
def __init__(self, prefix, time=0):
self.prefix = prefix
self.time = time
def __call__(self, method):
@functools.wraps(method)
def wrapper(cls, *args):
if args:
key = self.prefix + ':' + '-'.join(map(str, args))
else:
key = self.prefix
value = simple_cache.get(key)
if value is None:
value = method(cls, *args)
simple_cache.set(key, value, self.time)
return value
return wrapper
def cached_clear(key):
simple_cache.delete(key)
class autocached(object):
"""Cache decorator, an easy way to manage redis_cache.
The result key will be like: prefix:arg1-arg2
"""
def __init__(self, prefix, time=0):
self.prefix = prefix
self.time = time
def __call__(self, method):
@functools.wraps(method)
def wrapper(cls, *args):
key = options.site_cache_prefix+self.prefix
if args:
key = options.site_cache_prefix+self.prefix + '-'.join(map(str, args))
# else:
# key = self.prefix
value = complex_cache.get(key)
if value is None:
value = method(cls, *args)
v = cPickle.dumps(value)
complex_cache.set(key, v, self.time)
else:
logging.debug("complex_cache load from cache", key)
value = cPickle.loads(value)
return value
return wrapper
def autocache_del(key):
logging.debug("complex_cache delete from cache", key)
key = options.site_cache_prefix + key
complex_cache.delete(key)
# if isinstance(key, list):
# for k in key:
# complex_cache.delete(k)
# else:
# complex_cache.delete(key)
def autocache_del_pattern(key_pattern):
logging.debug("complex_cache delete pattern from cache", key_pattern)
keys = complex_cache.keys(options.site_cache_prefix+key_pattern)
if keys:
for key in keys:
complex_cache.delete(key)
else:
logging.debug("del pattern keys is none")
def autocache_get(key):
return complex_cache.get(options.site_cache_prefix+key)
def autocache_set(key, value, time=0):
complex_cache.set(options.site_cache_prefix+key, value, time)
def autocache_mget(keys):
return complex_cache.mget(keys)
def autocache_incr(key, value):
return complex_cache.incr(options.site_cache_prefix+key, value)
def autocache_hdel(key, id):
complex_cache.hdel(options.site_cache_prefix+key, id)
def autocache_hget(key, id):
return complex_cache.hget(options.site_cache_prefix+key, id)
def autocache_hset(key, id):
complex_cache.hset(options.site_cache_prefix+key, id)
def autocache_zadd(key, value, score):
complex_cache.zadd(options.site_cache_prefix+key, str(value), score)
def autocache_zrange(key, start, end):
return complex_cache.zrange(options.site_cache_prefix+key, start, end)
def get_simple_cache_list(model, id_list, key_prefix, time=600, site_prefix=None):
if site_prefix is None:
site_prefix = options.site_cache_prefix
if not id_list:
return {}
id_list = set(id_list)
data = cache.get_multi(id_list, key_prefix=site_prefix+key_prefix)
missing = id_list - set(data)
if missing:
dct = {}
for item in model.query.filter_by(id__in=missing).all():
dct[item.id] = item
cache.set_multi(dct, time=time, key_prefix=key_prefix)
data.update(dct)
return data
def get_cache_list(model, id_list, key_hash, time=600, site_prefix=None):
if site_prefix is None:
site_prefix = options.site_cache_prefix
if not id_list:
return {}
int_id_list = []
data_id_list = []
data_dict= dict()
for id in id_list:
int_id_list.append(str(id))
# str_id_list = complex_cache.hkeys('people')
# print str_id_list
if len(int_id_list)>0:
data = complex_cache.hmget(site_prefix+key_hash, int_id_list)
# return data
# id_list = set(id_list)
for d in data:
if d:
d_value = cPickle.loads(d)
#print d_value.id, d_value, type(d_value)
data_dict[d_value.id] = d_value
data_id_list.append(str(d_value.id))
missing = set(int_id_list) - set(data_id_list)
# print "missing", missing
if len(missing) > 0:
# print "missing2", missing
dct = {}
for item in model.query.filter_by(id__in=missing).all():
# print "item id", item.id
dct[item.id] = cPickle.dumps(item)
data_dict[item.id] = item
complex_cache.hmset(site_prefix+key_hash, dct)
return data_dict