At times your application might need to store the results of some expensive operation so as to not perform the expensive recomputation. This is where caching comes in, and GeniePy comes with built-in support for caching.

GeniePy uses the aiocache library. The default backend for storing information is in-memory, but you're free to use Redis or Memcache if you wish.

Configuration

Set the CACHE_BACKEND environment variable to one of memory, redis, or memcache.

With that environment variable in place, we can move on to configuring the individual cache backends.

Memory

You don't need any extra configuration for using the process's memory as the caching backend.

Please note that in a production setting, this value is not recommended especially if you're running multiple instances of your application. If two successive requests end up hitting different application processes, in one a cache.get might succeed while in the other one it might not.

Redis

Specify valid values for the following two environment variables:

  1. CACHE_REDIS_HOST: the hostname where your Redis instance is running
  2. CACHE_REDIS_PORT: the port on which Redis is listening

Memcache

Specify valid values for the following two environment variables:

  1. CACHE_MEMCACHE_HOST: the hostname where your Memcache instance is running
  2. CACHE_MEMCACHE_PORT: the port on which Memcache is listening

Usage

The code around caching uses the aiocache interface. There is detailed documentation here.

Generally speaking, you can use get or set functions to interact with the cache.

async def example():
    # set a key to a given value
    await cache.set("key", "value")

    # get the value for a key
    result = await cache.get("key")