A Declarative Caching Library for Human
Project description
hucache
A Declarative Caching Library for Human
Usage
Construct a cache instance
Construct from a redis conn
>>> from hucache import CacheFactory
>>> redis_client = fakeredis.FakeStrictRedis()
>>> cache = CacheFactory.from_store_conn("redis", redis_client, prefix="test:")
Construct from a redis url like "redis://xxxx"
>>> cache = CacheFactory.from_store_url("redis", redis_url, prefix="test:")
Use the cache on function
>>> @cache("add:{a}:{b}")
... def add(a, b, c=1):
... return a + b + c
>>> add(3, 2)
6
The third argument c is not used in the cache key "add:{a}:{b}",
so the result will not change.
>>> add(3, b=3)
7
>>> add(3, b=3, c=2)
7
invalidate the cache
>>> add.invalidate(3, 3)
>>> add(3, b=3, c=2)
8
You can use positional argument or keywords argument as you wish.
>>> @cache("mul:{a}:{b}:{c}")
... def mul(a, b, c=2):
... return a * b * c
>>> mul(3, 4)
24
>>> mul(3, 4) == mul(3, c=2, b=4) == mul(c=2, a=3, b=4) == mul(3, 4, 2)
True
Use the cache on class
>>> class Example(object):
... def __init__(self, incr):
... self.incr = incr
... @cache("example.add:{a}:{b}:{c}")
... def add(self, a, b, c=1):
... return a + b + c + self.incr
... @cache("example.mul:{a}:{b}:{c}")
... @classmethod
... def mul(cls, a, b, c=2):
... return a * b * c
>>> Example(1).add(2, 3)
7
>>> Example(2).add(a=2, b=3) == Example(3).add(b=3, c=1, a=2)
True
>>> Example.mul(3,4)
24
>>> Example.mul(3,4) == Example.mul(3, b=4, c=2) == Example.mul(b=4,c=2,a=3)
True
>>> @cache("add_ref:{a.id}:{b.id}")
... def add_ref(a, b, c=1):
... return a.id + b.id + c
>>> from collections import namedtuple
>>> Point = namedtuple('Point', 'id')
>>> add_ref(Point(3), Point(4))
8
Custom timeout
Default timeout is 1 hour, you can change default timeout at the factory
>>> cache = CacheFactory.from_store_conn("redis", redis_client, default_timeout=300)
Or you can change it per function
>>> @cache("add:{a}:{b}", timeout=60)
... def add(a, b, c=1):
... return a + b + c
Change Serializer
Default serializer is json, you can change it with pickle
>>> cache = CacheFactory.from_store_conn("redis", redis_client, format_type="PICKLE")
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
hucache-0.10.0.tar.gz
(5.8 kB
view details)
File details
Details for the file hucache-0.10.0.tar.gz
.
File metadata
- Download URL: hucache-0.10.0.tar.gz
- Upload date:
- Size: 5.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.11.4
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9313399eb69d59286b731d1e661049440a6455db330106eeb3d7ed74ab1eeae3 |
|
MD5 | 3bfa75e09ac30b5acbe36448e4165585 |
|
BLAKE2b-256 | 20412e0af9479c1dc7b0e6a61e68afe1ce5bf728124565a3eea1eb83a16b1fde |