python memoize / cache decorators(另请参阅https://pythonhosted.org/Flask-Cache/#flask.ext.cache.Cache.me

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python memoize / cache decorators(另请参阅https://pythonhosted.org/Flask-Cache/#flask.ext.cache.Cache.me相关的知识,希望对你有一定的参考价值。

from functools import wraps


def memoize(obj):
    '''Memoization decorator for callables'''
    memo = obj.memo = {}

    @wraps(obj)
    def memoizer(*args, **kwargs):
        key = str(args) + str(kwargs)
        if key not in memo:
            memo[key] = obj(*args, **kwargs)
        return memo[key]

    return memoizer
def memoize(timeout=60):
    '''
    Memoization with django's cache backend

    Refer:
        - https://djangosnippets.org/snippets/564/
        - http://pythonhosted.org/django-memoize/
    '''
    from hashlib import sha1
    from django.core.cache import cache
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def _func(*args, **kwargs):
            key_seed = ':'.join([
                'memoize',
                str(func.__module__),
                str(func.__name__),
                str(args),
                str(kwargs),
            ])
            key = sha1(key_seed).hexdigest()
            result = cache.get(key)
            if result is None:
                result = func(*args, **kwargs)
                cache.set(key, result, timeout)
            return result
        return _func
    return decorator
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import six
from functools import wraps
from lib.cache import cache as default_cache
from flask import request


def cache_by_args(timeout=5 * 60, prefix='', cache=None):
    """
    Use cases:

    @cache_by_args(3600)
    def f(x, y):
        pass

    from some.package import func
    res = cache_by_args(3600)(func)(x, y)
    """
    cache = cache or default_cache

    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            force_update = kwargs.pop('_force_update', False)

            cache_key = '{0}{1}.{2}:{3}'.format(
                prefix, f.__module__, f.__name__, ','.join(
                    six.text_type(a)
                    for a in list(args) +
                    ['{}={}'.format(k, v) for k, v in kwargs.items()]))

            if not (force_update or request.cache_control.no_cache):
                rv = cache.get(cache_key)
                if rv is not None:
                    return rv

            rv = f(*args, **kwargs)
            cache.set(cache_key, rv, timeout=timeout)
            return rv

        return decorated_function

    return decorator

以上是关于python memoize / cache decorators(另请参阅https://pythonhosted.org/Flask-Cache/#flask.ext.cache.Cache.me的主要内容,如果未能解决你的问题,请参考以下文章

lodash _.memoize

Python decorator module

python 使用Python装饰器进行Memoize

什么是 memoization 以及如何在 Python 中使用它?

python memoize.py

python3_原生 LRU 缓存