Persistent And In-Memory Storage¶
SimplePlugin provides Storage
and
MemStorage
classes with dict
-like interface
to store arbitrary data between plugin calls.
A Storage/MemStorage instance supports most of Python dict
methods
and can hold any Python picklable objects.
The Storage
class stores data on disk.
It also can be used as a context manager along with
with
statement. To create a Storage instance for the current plugin you need to call
get_storage
method for your Plugin instance, e.g.:
with plugin.get_storage() as storage: # Create a storage object
storage['key1'] = value1 # Store data
value2 = storage['key2'] # Retrieve data
After exiting a with
block a Storage object is invalidated.
To use the storage again you need to create a new Storage instance.
Storage contents are saved to disk only for a newly created storage or if the storage contents
have been changed. This reduces the number of write operations in cases when we need only to read stored data.
get_storage
method takes an optional parameter
which is the name of a storage file, so you can have several different storages in your plugin.
Storage files are stored in the plugin’s profile folder which is
special://profile/addon_data/your.plugin.id
.
The MemStorage
class stores data in memory.
The storage contents last as long as Kodi runs. MemStorage is thread-safe
and can be used for communication between different Python
processes. That is, MemStorage instances with the same IDs created in different
processes share the same contents.
Warning
MemStorage does not allow to modify mutable objects in-place. You need to assign them to variables first, modify and then store them back to a MemStorage instance.
Example:
storage = MemStorage('foo')
some_list = storage['bar']
some_list.append('spam')
storage['bar'] = some_list