aiocache


Nameaiocache JSON
Version 0.12.2 PyPI version JSON
download
home_pagehttps://github.com/aio-libs/aiocache
Summarymulti backend asyncio cache
upload_time2023-08-06 20:31:22
maintainer
docs_urlNone
authorManuel Miranda
requires_python
license
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            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 allows you to save any Python object into your cache. Currently supporting: StringSerializer, PickleSerializer, JsonSerializer, and MsgPackSerializer. But you can also build custom ones.
- **plugins**: Implement a hooks system that allows to execute extra behavior before and after of each command.

 If you are missing an implementation of backend, serializer or plugin you think it could be interesting for the package, do not hesitate to open a new issue.

.. image:: docs/images/architecture.png
  :align: center

Those 3 entities combine during some of the cache operations to apply the desired command (backend), data transformation (serializer) and pre/post hooks (plugins). To have a better vision of what happens, here you can check how ``set`` function works in ``aiocache``:

.. image:: docs/images/set_operation_flow.png
  :align: center


Amazing examples
================

In `examples folder <https://github.com/argaen/aiocache/tree/master/examples>`_ you can check different use cases:

- `Sanic, Aiohttp and Tornado <https://github.com/argaen/aiocache/tree/master/examples/frameworks>`_
- `Python object in Redis <https://github.com/argaen/aiocache/blob/master/examples/python_object.py>`_
- `Custom serializer for compressing data <https://github.com/argaen/aiocache/blob/master/examples/serializer_class.py>`_
- `TimingPlugin and HitMissRatioPlugin demos <https://github.com/argaen/aiocache/blob/master/examples/plugins.py>`_
- `Using marshmallow as a serializer <https://github.com/argaen/aiocache/blob/master/examples/marshmallow_serializer_class.py>`_
- `Using cached decorator <https://github.com/argaen/aiocache/blob/master/examples/cached_decorator.py>`_.
- `Using multi_cached decorator <https://github.com/argaen/aiocache/blob/master/examples/multicached_decorator.py>`_.



Documentation
=============

- `Usage <http://aiocache.readthedocs.io/en/latest>`_
- `Caches <http://aiocache.readthedocs.io/en/latest/caches.html>`_
- `Serializers <http://aiocache.readthedocs.io/en/latest/serializers.html>`_
- `Plugins <http://aiocache.readthedocs.io/en/latest/plugins.html>`_
- `Configuration <http://aiocache.readthedocs.io/en/latest/configuration.html>`_
- `Decorators <http://aiocache.readthedocs.io/en/latest/decorators.html>`_
- `Testing <http://aiocache.readthedocs.io/en/latest/testing.html>`_
- `Examples <https://github.com/argaen/aiocache/tree/master/examples>`_


.. _redis: https://github.com/redis/redis-py
.. _aiomcache: https://github.com/aio-libs/aiomcache

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/aio-libs/aiocache",
    "name": "aiocache",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Manuel Miranda",
    "author_email": "manu.mirandad@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/38/46/5c76e8f6dc3a550c93785c0daaff8140e3515e0ac089d47ef9c9f0ad0288/aiocache-0.12.2.tar.gz",
    "platform": null,
    "description": "aiocache\n########\n\nAsyncio cache supporting multiple backends (memory, redis and memcached).\n\n.. image:: https://travis-ci.org/argaen/aiocache.svg?branch=master\n  :target: https://travis-ci.org/argaen/aiocache\n\n.. image:: https://codecov.io/gh/argaen/aiocache/branch/master/graph/badge.svg\n  :target: https://codecov.io/gh/argaen/aiocache\n\n.. image:: https://badge.fury.io/py/aiocache.svg\n  :target: https://pypi.python.org/pypi/aiocache\n\n.. image:: https://img.shields.io/pypi/pyversions/aiocache.svg\n  :target: https://pypi.python.org/pypi/aiocache\n\n.. image:: https://api.codacy.com/project/badge/Grade/96f772e38e63489ca884dbaf6e9fb7fd\n  :target: https://www.codacy.com/app/argaen/aiocache\n\n.. image:: https://img.shields.io/badge/code%20style-black-000000.svg\n    :target: https://github.com/ambv/black\n\nThis library aims for simplicity over specialization. All caches contain the same minimum interface which consists on the following functions:\n\n- ``add``: Only adds key/value if key does not exist.\n- ``get``: Retrieve value identified by key.\n- ``set``: Sets key/value.\n- ``multi_get``: Retrieves multiple key/values.\n- ``multi_set``: Sets multiple key/values.\n- ``exists``: Returns True if key exists False otherwise.\n- ``increment``: Increment the value stored in the given key.\n- ``delete``: Deletes key and returns number of deleted items.\n- ``clear``: Clears the items stored.\n- ``raw``: Executes the specified command using the underlying client.\n\n\n.. role:: python(code)\n  :language: python\n\n.. contents::\n\n.. section-numbering:\n\n\nInstalling\n==========\n\n- ``pip install aiocache``\n- ``pip install aiocache[redis]``\n- ``pip install aiocache[memcached]``\n- ``pip install aiocache[redis,memcached]``\n- ``pip install aiocache[msgpack]``\n\n\nUsage\n=====\n\nUsing a cache is as simple as\n\n.. code-block:: python\n\n    >>> import asyncio\n    >>> from aiocache import Cache\n    >>> cache = Cache(Cache.MEMORY) # Here you can also use Cache.REDIS and Cache.MEMCACHED, default is Cache.MEMORY\n    >>> with asyncio.Runner() as runner:\n    >>>     runner.run(cache.set('key', 'value'))\n    True\n    >>>     runner.run(cache.get('key'))\n    'value'\n\nOr as a decorator\n\n.. code-block:: python\n\n    import asyncio\n\n    from collections import namedtuple\n\n    from aiocache import cached, Cache\n    from aiocache.serializers import PickleSerializer\n    # With this we can store python objects in backends like Redis!\n\n    Result = namedtuple('Result', \"content, status\")\n\n\n    @cached(\n        ttl=10, cache=Cache.REDIS, key=\"key\", serializer=PickleSerializer(), port=6379, namespace=\"main\")\n    async def cached_call():\n        print(\"Sleeping for three seconds zzzz.....\")\n        await asyncio.sleep(3)\n        return Result(\"content\", 200)\n\n\n    async def run():\n        await cached_call()\n        await cached_call()\n        await cached_call()\n        cache = Cache(Cache.REDIS, endpoint=\"127.0.0.1\", port=6379, namespace=\"main\")\n        await cache.delete(\"key\")\n\n    if __name__ == \"__main__\":\n        asyncio.run(run())\n\nThe 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`.\n\n\nYou can also setup cache aliases so its easy to reuse configurations\n\n.. code-block:: python\n\n  import asyncio\n\n  from aiocache import caches\n\n  # You can use either classes or strings for referencing classes\n  caches.set_config({\n      'default': {\n          'cache': \"aiocache.SimpleMemoryCache\",\n          'serializer': {\n              'class': \"aiocache.serializers.StringSerializer\"\n          }\n      },\n      'redis_alt': {\n          'cache': \"aiocache.RedisCache\",\n          'endpoint': \"127.0.0.1\",\n          'port': 6379,\n          'timeout': 1,\n          'serializer': {\n              'class': \"aiocache.serializers.PickleSerializer\"\n          },\n          'plugins': [\n              {'class': \"aiocache.plugins.HitMissRatioPlugin\"},\n              {'class': \"aiocache.plugins.TimingPlugin\"}\n          ]\n      }\n  })\n\n\n  async def default_cache():\n      cache = caches.get('default')   # This always returns the SAME instance\n      await cache.set(\"key\", \"value\")\n      assert await cache.get(\"key\") == \"value\"\n\n\n  async def alt_cache():\n      cache = caches.create('redis_alt')   # This creates a NEW instance on every call\n      await cache.set(\"key\", \"value\")\n      assert await cache.get(\"key\") == \"value\"\n\n\n  async def test_alias():\n      await default_cache()\n      await alt_cache()\n\n      await caches.get(\"redis_alt\").delete(\"key\")\n\n\n  if __name__ == \"__main__\":\n      asyncio.run(test_alias())\n\n\nHow does it work\n================\n\nAiocache provides 3 main entities:\n\n- **backends**: Allow you specify which backend you want to use for your cache. Currently supporting: SimpleMemoryCache, RedisCache using redis_ and MemCache using aiomcache_.\n- **serializers**: Serialize and deserialize the data between your code and the backends. This allows you to save any Python object into your cache. Currently supporting: StringSerializer, PickleSerializer, JsonSerializer, and MsgPackSerializer. But you can also build custom ones.\n- **plugins**: Implement a hooks system that allows to execute extra behavior before and after of each command.\n\n If you are missing an implementation of backend, serializer or plugin you think it could be interesting for the package, do not hesitate to open a new issue.\n\n.. image:: docs/images/architecture.png\n  :align: center\n\nThose 3 entities combine during some of the cache operations to apply the desired command (backend), data transformation (serializer) and pre/post hooks (plugins). To have a better vision of what happens, here you can check how ``set`` function works in ``aiocache``:\n\n.. image:: docs/images/set_operation_flow.png\n  :align: center\n\n\nAmazing examples\n================\n\nIn `examples folder <https://github.com/argaen/aiocache/tree/master/examples>`_ you can check different use cases:\n\n- `Sanic, Aiohttp and Tornado <https://github.com/argaen/aiocache/tree/master/examples/frameworks>`_\n- `Python object in Redis <https://github.com/argaen/aiocache/blob/master/examples/python_object.py>`_\n- `Custom serializer for compressing data <https://github.com/argaen/aiocache/blob/master/examples/serializer_class.py>`_\n- `TimingPlugin and HitMissRatioPlugin demos <https://github.com/argaen/aiocache/blob/master/examples/plugins.py>`_\n- `Using marshmallow as a serializer <https://github.com/argaen/aiocache/blob/master/examples/marshmallow_serializer_class.py>`_\n- `Using cached decorator <https://github.com/argaen/aiocache/blob/master/examples/cached_decorator.py>`_.\n- `Using multi_cached decorator <https://github.com/argaen/aiocache/blob/master/examples/multicached_decorator.py>`_.\n\n\n\nDocumentation\n=============\n\n- `Usage <http://aiocache.readthedocs.io/en/latest>`_\n- `Caches <http://aiocache.readthedocs.io/en/latest/caches.html>`_\n- `Serializers <http://aiocache.readthedocs.io/en/latest/serializers.html>`_\n- `Plugins <http://aiocache.readthedocs.io/en/latest/plugins.html>`_\n- `Configuration <http://aiocache.readthedocs.io/en/latest/configuration.html>`_\n- `Decorators <http://aiocache.readthedocs.io/en/latest/decorators.html>`_\n- `Testing <http://aiocache.readthedocs.io/en/latest/testing.html>`_\n- `Examples <https://github.com/argaen/aiocache/tree/master/examples>`_\n\n\n.. _redis: https://github.com/redis/redis-py\n.. _aiomcache: https://github.com/aio-libs/aiomcache\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "multi backend asyncio cache",
    "version": "0.12.2",
    "project_urls": {
        "Homepage": "https://github.com/aio-libs/aiocache"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3cced7dccae884f2840d0df9ea4103a3f50d87ac6c9399d2f6f0a2f1208ac063",
                "md5": "c972eaf325ca16f3af52646a6713b65b",
                "sha256": "9b6fa30634ab0bfc3ecc44928a91ff07c6ea16d27d55469636b296ebc6eb5918"
            },
            "downloads": -1,
            "filename": "aiocache-0.12.2-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c972eaf325ca16f3af52646a6713b65b",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": null,
            "size": 28055,
            "upload_time": "2023-08-06T20:31:21",
            "upload_time_iso_8601": "2023-08-06T20:31:21.205734Z",
            "url": "https://files.pythonhosted.org/packages/3c/ce/d7dccae884f2840d0df9ea4103a3f50d87ac6c9399d2f6f0a2f1208ac063/aiocache-0.12.2-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "38465c76e8f6dc3a550c93785c0daaff8140e3515e0ac089d47ef9c9f0ad0288",
                "md5": "e047e7ac44e101e5fa505876b3defe2d",
                "sha256": "b41c9a145b050a5dcbae1599f847db6dd445193b1f3bd172d8e0fe0cb9e96684"
            },
            "downloads": -1,
            "filename": "aiocache-0.12.2.tar.gz",
            "has_sig": false,
            "md5_digest": "e047e7ac44e101e5fa505876b3defe2d",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 131851,
            "upload_time": "2023-08-06T20:31:22",
            "upload_time_iso_8601": "2023-08-06T20:31:22.478379Z",
            "url": "https://files.pythonhosted.org/packages/38/46/5c76e8f6dc3a550c93785c0daaff8140e3515e0ac089d47ef9c9f0ad0288/aiocache-0.12.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-08-06 20:31:22",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "aio-libs",
    "github_project": "aiocache",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "requirements": [],
    "lcname": "aiocache"
}
        
Elapsed time: 0.43641s