Kivy - Cache Manager



In Kivy framework, the Cache class stores one or more Python objects by assigning them as value of a unique key. Kivy's Cache manager controls the objects in it by either imposing a limit to the number of objects in it, or keeping a timeout limit to their access.

The Cache class is defined in the "kivy.cache" module. It includes the static methods: register(), append(), get(), etc.

To start with, you need to register a Category in the Cache manager by setting the maximum number of objects and the timeout.

from kivy.cache import Cache
Cache.register(category='mycache', limit=10, timeout=5)

You can now add upto 10 Python objects, each with a unique key.

key = 'objectid'
instance = Label(text=text)
Cache.append('mycache', key, instance)

The get() method retrieves an object from the cache.

instance = Cache.get('mycache', key)

The Cache class defines the following methods and properties

register() Method

This method registers a new category in the cache with the specified limit. It has the following parameters −

  • category − A string identifier of the category.

  • limit − Maximum number of objects allowed in the cache. If None, no limit is applied.

  • timeout − Time after which the object will be removed from cache.

append() Method

This method add a new object to the cache. Following parameters are defined −

  • category − string identifier of the category.

  • key − Unique identifier of the object to store.

  • obj − Object to store in cache.

  • timeout − Time after which to object will be deleted if it has not been used. This raises ValueError if None is used as key.

get() Method

This method is used to get a object from the cache, with the following parameters −

  • category − string identifier of the category..

  • key − Unique identifier of the object in the store..

  • default − Default value to be returned if the key is not found.

Example

Take a look at the following example −

from kivy.cache import Cache
from kivy.uix.button import Button
from kivy.uix.label import Label

Cache.register(category='CacheTest', limit=5, timeout=15)

b1 = Button(text='Button Cache Test')
Cache.append(category='CacheTest', key='Button', obj=b1)

l1 = Label(text='Label Cache Test')
Cache.append(category='CacheTest', key='Label', obj=l1)

ret = (Cache.get('CacheTest', 'Label').text)
print (ret)

Output

It will produce the following output −

Label Cache Test
Advertisements