freshcrate
Home > Frameworks > aiocache

aiocache

multi backend asyncio cache

Description

aiocache ######## Asyncio cache supporting multiple backends (memory, redis and memcached). .. image:: https://travis-ci.org/argaen/aiocache.svg?branch=master :target: https://travis-ci.org/argaen/aiocache .. image:: https://codecov.io/gh/argaen/aiocache/branch/master/graph/badge.svg :target: https://codecov.io/gh/argaen/aiocache .. image:: https://badge.fury.io/py/aiocache.svg :target: https://pypi.python.org/pypi/aiocache .. image:: https://img.shields.io/pypi/pyversions/aiocache.svg :target: https://pypi.python.org/pypi/aiocache .. image:: https://api.codacy.com/project/badge/Grade/96f772e38e63489ca884dbaf6e9fb7fd :target: https://www.codacy.com/app/argaen/aiocache .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black This library aims for simplicity over specialization. All caches contain the same minimum interface which consists on the following functions: - ``add``: Only adds key/value if key does not exist. - ``get``: Retrieve value identified by key. - ``set``: Sets key/value. - ``multi_get``: Retrieves multiple key/values. - ``multi_set``: Sets multiple key/values. - ``exists``: Returns True if key exists False otherwise. - ``increment``: Increment the value stored in the given key. - ``delete``: Deletes key and returns number of deleted items. - ``clear``: Clears the items stored. - ``raw``: Executes the specified command using the underlying client. .. role:: python(code) :language: python .. contents:: .. section-numbering: Installing ========== - ``pip install aiocache`` - ``pip install aiocache[redis]`` - ``pip install aiocache[memcached]`` - ``pip install aiocache[redis,memcached]`` - ``pip install aiocache[msgpack]`` Usage ===== Using a cache is as simple as .. code-block:: python >>> import asyncio >>> from aiocache import Cache >>> cache = Cache(Cache.MEMORY) # Here you can also use Cache.REDIS and Cache.MEMCACHED, default is Cache.MEMORY >>> with asyncio.Runner() as runner: >>> runner.run(cache.set('key', 'value')) True >>> runner.run(cache.get('key')) 'value' Or as a decorator .. code-block:: python import asyncio from collections import namedtuple from aiocache import cached, Cache from aiocache.serializers import PickleSerializer # With this we can store python objects in backends like Redis! Result = namedtuple('Result', "content, status") @cached( ttl=10, cache=Cache.REDIS, key="key", serializer=PickleSerializer(), port=6379, namespace="main") async def cached_call(): print("Sleeping for three seconds zzzz.....") await asyncio.sleep(3) return Result("content", 200) async def run(): await cached_call() await cached_call() await cached_call() cache = Cache(Cache.REDIS, endpoint="127.0.0.1", port=6379, namespace="main") await cache.delete("key") if __name__ == "__main__": asyncio.run(run()) The recommended approach to instantiate a new cache is using the `Cache` constructor. However you can also instantiate directly using `aiocache.RedisCache`, `aiocache.SimpleMemoryCache` or `aiocache.MemcachedCache`. You can also setup cache aliases so its easy to reuse configurations .. code-block:: python import asyncio from aiocache import caches # You can use either classes or strings for referencing classes caches.set_config({ 'default': { 'cache': "aiocache.SimpleMemoryCache", 'serializer': { 'class': "aiocache.serializers.StringSerializer" } }, 'redis_alt': { 'cache': "aiocache.RedisCache", 'endpoint': "127.0.0.1", 'port': 6379, 'timeout': 1, 'serializer': { 'class': "aiocache.serializers.PickleSerializer" }, 'plugins': [ {'class': "aiocache.plugins.HitMissRatioPlugin"}, {'class': "aiocache.plugins.TimingPlugin"} ] } }) async def default_cache(): cache = caches.get('default') # This always returns the SAME instance await cache.set("key", "value") assert await cache.get("key") == "value" async def alt_cache(): cache = caches.create('redis_alt') # This creates a NEW instance on every call await cache.set("key", "value") assert await cache.get("key") == "value" async def test_alias(): await default_cache() await alt_cache() await caches.get("redis_alt").delete("key") if __name__ == "__main__": asyncio.run(test_alias()) How does it work ================ Aiocache provides 3 main entities: - **backends**: Allow you specify which backend you want to use for your cache. Currently supporting: SimpleMemoryCache, RedisCache using redis_ and MemCache using aiomcache_. - **serializers**: Serialize and deserialize the data between your code and the backends. This

Release History

VersionChangesUrgencyDate
0.12.3Imported from PyPI (0.12.3)Low4/21/2026
v0.12.3* Added SSL support for Redis backend. * Fixed memory leak in ``SimpleMemoryBackend._redlock_release()``. * Fixed exception for cache proxy creation when passing ``None``.Low9/25/2024
v0.12.2* Fixed an error when the ``pairs`` argument to ``.multi_set()`` doesn't support ``len()``.Low8/6/2023
v0.12.1* Added ``skip_cache_func`` to dynamically skip caching certain results. * Removed typing support due to producing unresolvable errors (until v1.0). * Stopped installing ``tests`` as part of the package.Low4/23/2023
v0.12.0* Added ``async with`` support to ``BaseCache``. * Added initial typing support. * Migrated to ``redis`` library (``aioredis`` is no longer supported). * ``SimpleMemoryBackend`` now has a cache per instance, rather than a global cache. * Improved support for ``build_key(key, namespace)`` [#569](https://github.com/aio-libs/aiocache/issues/569) -- Padraic Shafer * Removed deprecated ``loop`` parameters. * Removed deprecated ``cache`` parameter from ``create()``. * Added support for keyword argumenLow1/13/2023
0.11.1- Don't hardcode import redis and memcached in factory #461 - Manuel MirandaLow10/14/2020
0.11.0- Support str for timeout and ttl #454 - Manuel Miranda - Add aiocache_wait_for_write decorator param #448 - Manuel Miranda - Extend and improve usage of Cache class #446 - Manuel Miranda - Add caches.add functionality #440 - Manuel Miranda - Use raw msgpack attribute for loads #439 - Manuel Miranda - Add docs regarding plugin timeouts and multicached #438 - Manuel Miranda - Fix typehints in lock.py #434 - Aviv - Use pytest_configure instead of pytest_namespace #436 - Manuel Miranda - AdLow10/14/2020
0.10.1* Cancel the previous ttl timer if exists when setting a new value in the in-memory cache [#424](https://github.com/argaen/aiocache/issues/424) - Minh Tu Le * Add python 3.7 to CI, now its supported! [#420](https://github.com/argaen/aiocache/issues/420) - Manuel Miranda * Add function as parameter for key_builder [#417](https://github.com/argaen/aiocache/issues/417) - Manuel Miranda * Always use __name__ when getting logger [#412](https://github.com/argaen/aiocache/issues/412) - Mansur Low11/15/2018
0.10.0- Cache can be disabled in decorated functions using cache_read and cache_write #404 - Josep Cugat - Cache constructor can receive now default ttl #405 - Josep CugatLow6/18/2018
0.9.1* Single deploy step [#395](https://github.com/argaen/aiocache/issues/395) - Manuel Miranda * Catch ImportError when importing optional msgpack [#398](https://github.com/argaen/aiocache/issues/398) - Paweł Kowalski * Lazy load redis asyncio.Lock [#397](https://github.com/argaen/aiocache/issues/397) - Jordi SoucheironLow4/26/2018
0.9.0* Bug #389/propagate redlock exceptions [#394](https://github.com/argaen/aiocache/issues/394) - Manuel Miranda ___aexit__ was returning whether asyncio Event was removed or not. In some cases this was avoiding the context manager to propagate exceptions happening inside. Now its not returning anything and will raise always any exception raised from inside_ * Fix sphinx build [#392](https://github.com/argaen/aiocache/issues/392) - Manuel Miranda _Also add extra step in build pipeline Low4/24/2018
0.8.0* Add pypy support in build pipeline [#359](https://github.com/argaen/aiocache/issues/359) - Manuel Miranda * Fix multicached bug when using keys as an arg rather than kwarg [#356](https://github.com/argaen/aiocache/issues/356) - Manuel Miranda * Reuse cache when using decorators with alias [#355](https://github.com/argaen/aiocache/issues/355) - Manuel Miranda * Cache available from function.cache object for decorated functions [#354](https://github.com/argaen/aiocache/issues/354) - ManLow11/8/2017
0.7.2* Add key_builder param to caches to customize keys [#310](https://github.com/argaen/aiocache/issues/310) - Manuel Miranda * Propagate correct message on memcached connector error [#309](https://github.com/argaen/aiocache/issues/309) - Manuel MirandaLow7/30/2017
0.7.1* Remove explicit loop usages [#305](https://github.com/argaen/aiocache/issues/305) - Manuel Miranda * Remove bad logging configuration [#304](https://github.com/argaen/aiocache/issues/304) - Manuel Miranda Low7/15/2017
0.7.0* Upgrade to aioredis 0.3.3. - Manuel Miranda * Get CMD now returns values that evaluate to False correctly [#282](https://github.com/argaen/aiocache/issues/282) - Manuel Miranda * New locks public API exposed [#279](https://github.com/argaen/aiocache/issues/279) - Manuel Miranda _Users can now use aiocache.lock.RedLock and aiocache.lock.OptimisticLock_ * Memory now uses new NullSerializer [#273](https://github.com/argaen/aiocache/issues/273) - Manuel Miranda _Memory is a specialLow7/1/2017
0.6.0#### New * Cached supports stampede locking [#249](https://github.com/argaen/aiocache/issues/249) - Manuel Miranda * Memory redlock implementation [#241](https://github.com/argaen/aiocache/issues/241) - Manuel Miranda * Memcached redlock implementation [#240](https://github.com/argaen/aiocache/issues/240) - Manuel Miranda * Redis redlock implementation [#235](https://github.com/argaen/aiocache/issues/235) - Manuel Miranda * Add close function to clean up resources [#236](https://gLow6/5/2017
0.5.2Release 0.5.2Low5/15/2017
0.5.1Release 0.5.1Low5/7/2017
0.5.0Release 0.5.0Low4/29/2017
0.3.1Release 0.3.1Low2/13/2017
0.3.0Release 0.3.0Low1/12/2017
0.2.0Release 0.2.0Low12/14/2016
0.1.0Release 0.1.0Low10/24/2016

Dependencies & License Audit

Loading dependencies...

Similar Packages

pre-commitA framework for managing and maintaining multi-language pre-commit hooks.v4.6.0
azure-core-tracing-opentelemetryMicrosoft Azure Azure Core OpenTelemetry plugin Library for Pythonazure-template_0.1.0b6187637
spdx-toolsSPDX parser and tools.0.8.5
lacesDjango components that know how to render themselves.0.1.2
django-tasksA backport of Django's built in Tasks framework0.12.0