leafsummer
4/5/2016 - 2:21 AM

singleton pattern redis

singleton pattern redis

class RedisClient(redis.StrictRedis):

    """
    Singleton pattern 
    http://stackoverflow.com/questions/42558/python-and-the-singleton-pattern
    """

    _instance = {}

    def __init__(self, server):
        redis.StrictRedis.__init__(self, **server)

    def __new__(cls, *args):
        if not cls._instance.get(str(args)):
            cls._instance[str(args)] = super(RedisClient, cls).__new__(cls)
        return cls._instance[str(args)]


def singleton(_cls):
    inst = {}
    def getinstance(*args, **kwargs):
        if _cls not in inst:
            inst[_cls] = _cls(*args, **kwargs)
        return inst[_cls]
    return getinstance