def __init__(self, redis):
        """Initialize CacheCow with a redis client."""

        self.redis = redis

        # Set up Redis scripts responsible for retrieval and caching of the data

        # Get the cached value. If we don't have a cached value, we try to set
        # the flag (which expires) and return the previous state of the flag.
        # cache_key should be supplied as KEYS[1], flag_key as KEYS[2]
        self.get_cached_or_set_flag = self.redis.register_script("""
            local cached = redis.call('get', KEYS[1])
            if cached then
                return { 0, cached }
            else
                local flag = redis.call('get', KEYS[2])
                if flag then
                    return { 1, nil }
                else
                    redis.call("setex", KEYS[2], 1, 60)
                    return { 0, nil }
                end
            end
        """)

        # If the flag wasn't previously set, then we set it and we cache the
        # JSON doc. We do this unless the cache got invalidated and the flag
        # was removed.
        # cache_key should be supplied as KEYS[1], flag_key as KEYS[2]
        # cached object's data should be supplied as ARGV[1]
        self.cache = self.redis.register_script("""
            local flag = redis.call('get', KEYS[2])
            -- If we don't have the flag then don't set the cache since it was invalidated.
            if flag then
                redis.call("set", KEYS[1], ARGV[1])
                redis.call("del", KEYS[2])
            end
        """)
def __init__ ( self , redis ) : self . redis = redis self . get_cached_or_set_flag = self . redis . register_script ( """
            local cached = redis.call('get', KEYS[1])
            if cached then
                return { 0, cached }
            else
                local flag = redis.call('get', KEYS[2])
                if flag then
                    return { 1, nil }
                else
                    redis.call("setex", KEYS[2], 1, 60)
                    return { 0, nil }
                end
            end
        """ ) self . cache = self . redis . register_script ( """
            local flag = redis.call('get', KEYS[2])
            -- If we don't have the flag then don't set the cache since it was invalidated.
            if flag then
                redis.call("set", KEYS[1], ARGV[1])
                redis.call("del", KEYS[2])
            end
        """ )
Initialize CacheCow with a redis client.