From 959296b15ab8f7c5ecbb490c3c7087059c4747a7 Mon Sep 17 00:00:00 2001 From: Fabio Manganiello Date: Wed, 10 Jan 2018 18:47:25 +0100 Subject: [PATCH] Support for context variables and constants --- platypush/config/__init__.py | 37 +++++++++++++++++++++++++++ platypush/message/request/__init__.py | 7 +++++ 2 files changed, 44 insertions(+) diff --git a/platypush/config/__init__.py b/platypush/config/__init__.py index 9be7fa3e45..b02ab686b5 100644 --- a/platypush/config/__init__.py +++ b/platypush/config/__init__.py @@ -1,7 +1,9 @@ +import datetime import errno import logging import os import socket +import time import yaml """ Config singleton instance """ @@ -31,6 +33,11 @@ class Config(object): os.path.join(os.sep, 'etc', 'platypush', 'config.yaml'), ] + _default_constants = { + 'today': datetime.date.today().isoformat, + 'now': datetime.datetime.now().isoformat, + } + _workdir_location = os.path.join(os.environ['HOME'], '.local', 'share', 'platypush') def __init__(self, cfgfile=None): @@ -68,6 +75,9 @@ class Config(object): self.plugins = {} self.event_hooks = {} self.procedures = {} + self.constants = {} + + self._init_constants() self._init_components() @@ -115,6 +125,14 @@ class Config(object): else: self.plugins[key] = self._config[key] + def _init_constants(self): + if 'constants' in self._config: + self.constants = self._config['constants'] + + for (key,value) in self._default_constants.items(): + self.constants[key] = value + + @staticmethod def get_backends(): global _default_config_instance @@ -139,6 +157,25 @@ class Config(object): if _default_config_instance is None: _default_config_instance = Config() return _default_config_instance.procedures + @staticmethod + def get_constants(): + global _default_config_instance + if _default_config_instance is None: _default_config_instance = Config() + constants = {} + + for name in _default_config_instance.constants.keys(): + constants[name] = Config.get_constant(name) + return constants + + @staticmethod + def get_constant(name): + global _default_config_instance + if _default_config_instance is None: _default_config_instance = Config() + + if name not in _default_config_instance.constants: return None + value = _default_config_instance.constants[name] + return value() if callable(value) else value + @staticmethod def get_default_pusher_backend(): """ diff --git a/platypush/message/request/__init__.py b/platypush/message/request/__init__.py index 2f97b5be67..bc8d7bea4d 100644 --- a/platypush/message/request/__init__.py +++ b/platypush/message/request/__init__.py @@ -69,8 +69,15 @@ class Request(Message): def _expand_context(self, event_args=None, **context): + from platypush.config import Config + if event_args is None: event_args = copy.deepcopy(self.args) + constants = Config.get_constants() + context['constants'] = {} + for (name,value) in constants.items(): + context['constants'][name] = value + keys = [] if isinstance(event_args, dict): keys = event_args.keys()