From c3934e2a7e7cb5e713ea3f33314c5850be4819dc Mon Sep 17 00:00:00 2001 From: Fabio Manganiello Date: Sat, 12 Mar 2022 01:51:18 +0100 Subject: [PATCH] Script API for platform variables [closes #206] Added utility `platypush.context.Variable` class to simplify the interaction with platform variables in custom Python scripts. --- platypush/context/__init__.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/platypush/context/__init__.py b/platypush/context/__init__.py index 0f2a0239e3..f52fdbaed9 100644 --- a/platypush/context/__init__.py +++ b/platypush/context/__init__.py @@ -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: