# -*- 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'])