Skip to content
This repository has been archived by the owner on Dec 13, 2020. It is now read-only.

Caching

Roberto Prevato edited this page Oct 27, 2018 · 3 revisions

rocore includes a basic in-memory cache implementation, supporting expiration of cached items and capped lists.

from rocore.caching import Cache


def test_cache_item():
    cache = Cache()
    item = cache.get('cat')

    assert item is None

    cache.set('cat', 'Celine')
    item = cache.get('cat')

    assert 'Celine' == item.value

Cache with max size

By default, an instance of Cache keeps at most 500 items, removing the oldest as new ones are cached.

from rocore.caching import Cache

cache = Cache(max_size=20)

Cache with expiration policy

The following example shows how to configure a Cache object, to consider valid only objects that are cached in the last 30 seconds.

from rocore.caching import Cache, CachedItem

def expiration(item: CachedItem) -> bool:
    if (datetime.utcnow() - item.time).total_seconds() > 30:
        return True
    return False

cache = Cache(expiration_policy=expiration)