Skip to main content
Join the official Python Developers Survey 2018 and win valuable prizes: Start the survey!

A collection of cache helpers

Project description

https://travis-ci.org/suzaku/cachelper.svg?branch=master https://img.shields.io/pypi/v/cachelper.svg

Useful cache helpers in one package!

Sponsor

Install

pip install cachelper

Helpers

In memory cache

memoize

Caching function return values in memory.

import cachelper

@cachelper.memoize()
def fibo(n):
    if n in (0, 1):
        return 1
    return fibo(n - 1) + fibo(n - 2)

fibo(10)

Cache with Redis/Memcached

cache decorator

Add cache by decorating a function or method.

from redis import StrictRedis
from werkzeug.contrib.cache import RedisCache as _RedisCache

import cachelper

class RedisCache(_RedisCache, HelperMixin):
    '''werkzeug.contrib.cache.RedisCache mixed with HelperMixin'''

    def get_many(self, keys):
        return super().get_many(*keys)

rds = StrictRedis()
cache = RedisCache(rds)

@cache("key-{user_id}", timeout=300)
def get_name(user_id):
    # Fetch user name from database
    ...

You may use this mixin to create cache class of your own, as long as the following methods are provided:

  • def get(self, key)
  • def set(self, key, value, timeout=None)
  • def delete(self, key)
  • def get_many(self, keys)
  • def set_many(self, mapping, timeout=None)

cached function calls

Sometimes we don’t want to cache all calls to a specific function. So the decorator is not suitable, we may cache the call instead the function in this case:

def get_name(user_id):
    # Fetch user name from database
    ...

user_id = 42
key = "key-{user_id}".format(user_id=user_id)
cache.call(lambda: get_name(user_id), key, timeout=300)

cached multiple calls

For most cache backends, it’s much faster to get or set caches in bulk.

def get_name(user_id):
    # Fetch user name from database
    ...

user_ids = [1, 2, 42, 1984]
names = cache.map("key-{user_id}", get_name, user_ids, timeout=300)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Filename, size & hash SHA256 hash help File type Python version Upload date
cachelper-0.2.0.tar.gz (3.4 kB) Copy SHA256 hash SHA256 Source None Sep 2, 2017

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page