oslo.cache

4.1.1 · active · verified Thu Apr 16

oslo.cache is a Python library providing a generic caching mechanism for OpenStack projects, built as a wrapper around the `dogpile.cache` library. It offers support for memoization, key-value storage, and interfaces to common caching backends like Memcached and Redis. The current version is 4.1.1, and it typically follows the OpenStack release cycle, with new versions released regularly to align with OpenStack development milestones.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up and use `oslo.cache` with `oslo.config` for memoization. It initializes a cache region and applies a memoization decorator to a function. The first call to `get_heavy_computation_result` will execute the function, subsequent calls with the same arguments will retrieve the cached value. This example uses the `dogpile.cache.memory` backend, suitable for in-process caching. For production, backends like Memcached or Redis are recommended.

import os
from oslo_config import cfg
from oslo_cache import core as cache

CONF = cfg.CONF

def register_cache_opts():
    cache_group = cfg.OptGroup('cache', title='Cache Options')
    CONF.register_group(cache_group)
    cache.register_opts(CONF)

# Simulate loading configuration (e.g., from a config file)
# In a real OpenStack project, this would be handled by oslo.config setup
# For a simple script, we can set some options directly
CONF.set_default('backend', 'dogpile.cache.memory', group='cache')
CONF.set_default('expiration_time', 3600, group='cache')

register_cache_opts()
cache.configure(CONF)

example_cache_region = cache.create_region(name='my_app_cache')
MEMOIZE = cache.get_memoization_decorator(
    CONF, example_cache_region, 'cache'
)

@MEMOIZE()
def get_heavy_computation_result(value):
    print(f"Performing heavy computation for: {value}")
    return value * 2

if __name__ == '__main__':
    print(get_heavy_computation_result(10))
    print(get_heavy_computation_result(10)) # This should be cached
    print(get_heavy_computation_result(20))
    print(get_heavy_computation_result(20)) # This should be cached

view raw JSON →