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
# -*- coding: UTF-8 -*-
import redis
from django.conf import settings
class _RedisProxy(object):
"""redis proxy add prefix automatically."""
__connect_class = redis.StrictRedis
__pool = redis.ConnectionPool(**settings.DEFAULT_REDIS)
_client = __connect_class(connection_pool=__pool)
# add methods those are need to be hacked here
# 只支持单个获取,不支持批量获取,如mget
_hacked_methods = [
'set', 'get', 'setex', 'hget', 'hset', 'hincrby', 'hdel', 'hgetall',
'smembers', 'sadd', 'incr', 'delete', 'expire', 'decr',
'lpush', 'lrange', 'lrem', 'llen', 'sadd', 'srem', 'scard',
'sismember', 'rpop', 'keys', 'rpush', 'lpop', 'exists', "hexists",
"hmget", "hmset", "hscan_iter",
]
def __getattribute__(self, name):
attr = getattr(_RedisProxy._client, name)
if name in _RedisProxy._hacked_methods:
def newfunc(k, *args, **kwargs):
prefix = object.__getattribute__(self, 'prefix')
if isinstance(k, list):
k = [prefix + ':' + str(i) for i in k]
else:
k = prefix + ':' + k
result = attr(k, *args, **kwargs)
# bug fix for py35, json.loads does accept bytes!
if type(result) == bytes:
result = result.decode()
return result
return newfunc
return attr
def __init__(self, prefix):
self.prefix = prefix
@classmethod
def get_client(cls, prefix=''):
return cls(prefix)
_redis_proxy = _RedisProxy.get_client
sleep_action_fans_cache = _redis_proxy('sleep_action_fans_cache')
push_cache = _redis_proxy('push_cache')
sleep_noaction_fans_cache = _redis_proxy('sleep_noaction_fans_cache')
model_cache = _redis_proxy('model_c')
follow_cache = _RedisProxy('new_follow')
talos_tagrel_cache = _redis_proxy('tagrel')
page_cache = redis.StrictRedis(**settings.REDIS['page_cache'])