Script API for platform variables [closes #206]

Added utility `platypush.context.Variable` class to simplify the
interaction with platform variables in custom Python scripts.
This commit is contained in:
Fabio Manganiello 2022-03-12 01:51:18 +01:00
parent b3b2a7a805
commit c3934e2a7e
Signed by untrusted user: blacklight
GPG key ID: D90FBA7F76362774

View file

@ -3,6 +3,7 @@ import importlib
import logging
from threading import RLock
from typing import Optional, Callable, Any
from ..bus import Bus
from ..config import Config
@ -146,4 +147,33 @@ def get_or_create_event_loop():
return loop
class Variable:
"""
Utility class to wrap platform variables in your custom scripts.
Usage:
.. code-block:: python
# Pass `persisted=False` to get/set an in-memory variable
# on the Redis instance (default: the variable is
# persisted on the internal database)
var = Variable('myvar')
value = var.get()
var.set('new value')
"""
def __init__(self, name: str, persisted: bool = True):
self.name = name
plugin = get_plugin('variable')
self._get_action = getattr(plugin, 'get' if persisted else 'mget')
self._set_action = getattr(plugin, 'set' if persisted else 'mset')
def get(self) -> Optional[Any]:
return self._get_action(self.name).output.get(self.name)
def set(self, value: Any):
self._set_action(**{self.name: value})
# vim:sw=4:ts=4:et: