forked from platypush/platypush
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:
parent
b3b2a7a805
commit
c3934e2a7e
1 changed files with 30 additions and 0 deletions
|
@ -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:
|
||||
|
|
Loading…
Reference in a new issue