"""An example of a cache decorator."""

import json
from functools import wraps
from redis import StrictRedis


redis = StrictRedis()

def cached(func):
    """
    Decorator that caches the results of the function call.
    
    We use Redis in this example, but any cache (e.g. memcached) will work.
    We also assume that the result of the function can be seralized as JSON,
    which obviously will be untrue in many situations. Tweak as needed.
    """
    @wraps(func)
    def wrapper(*args, **kwargs):
        # Generate the cache key from the function's arguments.
        key_parts = [func.__name__] + list(args)
        key = '-'.join(key_parts)
        result = redis.get(key)

        if result is None:
            # Run the function and cache the result for next time.
            value = func(*args, **kwargs)
            value_json = json.dumps(value)
            redis.set(key, value_json)
        else:
            # Skip the function entirely and use the cached value instead.
            value_json = result.decode('utf-8')
            value = json.loads(value_json)

        return value
    return wrapper

# Usage:

@cached
def my_great_function():
    # The below calculation will run the first time this function is called.
    # On subsequent runs the result will be pulled from the cache instead.
    return list(range(10000))

By admin

Leave a Reply

Your email address will not be published.