Exemplo n.º 1
0
class SettingStorage(object):
    #
    def __init__(self, *args, topic='storage', connector=None, **kwargs):
        if isinstance(connector, RedisClient):
            self.__use_shared_connector = True
            self.__connector = connector
        else:
            self.__use_shared_connector = False
            self.__connector = RedisClient(**kwargs)
        #
        self.__topic = topic
        self.__default_key = ':'.join([self.__connector.CHANNEL_GROUP, self.__topic])
        #
        super(SettingStorage, self).__init__()
    #
    ##
    @property
    def connector(self):
        return self.__connector
    #
    ##
    def get(self, key:str):
        value = self.__open_connection().get(self.__gen_absolute_key(key))
        if isinstance(value, bytes):
            value = value.decode('utf-8')
        if isinstance(value, str):
            obj, err = json_loads(value)
            if err:
                raise err
            return obj
        return value
    #
    ##
    def store(self, key:str, obj:Union[dict,list,str,float,int,bool]):
        value, err = json_dumps(obj)
        if err:
            raise err
        return self.__open_connection().set(self.__gen_absolute_key(key), value)
    #
    ##
    def clear(self, key:str):
        return self.__open_connection().delete(self.__gen_absolute_key(key))
    #
    ##
    def close(self):
        if not self.__use_shared_connector:
            self.__connector.close()
        if LOG.isEnabledFor(logging.DEBUG):
            LOG.log(logging.DEBUG, "SettingStorage has closed")
    #
    #
    def __open_connection(self):
        return assure_not_null(self.__connector.rewind().connect(pinging=False, retrying=False))
    #
    def __gen_absolute_key(self, key):
        if key:
            return self.__default_key + ':' + str(key)
        return self.__default_key
Exemplo n.º 2
0
class AutoIncrement(object):
    #
    def __init__(self, topic='counter', connector=None, **kwargs):
        if isinstance(connector, RedisClient):
            self.__use_shared_connector = True
            self.__connector = connector
        else:
            self.__use_shared_connector = False
            self.__connector = RedisClient(**kwargs)
        #
        self.__topic = topic
        self.__default_key = ':'.join([self.__connector.CHANNEL_GROUP, self.__topic])
        #
        super(AutoIncrement, self).__init__()
    #
    ##
    @property
    def connector(self):
        return self.__connector
    #
    ##
    def init(self, label:Optional[str]=None, value:Optional[int]=0):
        return self.__open_connection().set(self.__gen_absolute_key(label), value, nx=True)
    #
    ##
    def incr(self, label:Optional[str]=None, amount:Optional[int]=1):
        return self.__open_connection().incr(self.__gen_absolute_key(label), amount=amount)
    #
    #
    def clear(self, label:Optional[str]=None):
        return self.__open_connection().delete(self.__gen_absolute_key(label))
    #
    #
    def reset(self, label:Optional[str]=None, value:Optional[int]=0):
        return self.__open_connection().set(self.__gen_absolute_key(label), value)
    #
    #
    def close(self):
        if not self.__use_shared_connector:
            self.__connector.close()
        if LOG.isEnabledFor(logging.DEBUG):
            LOG.log(logging.DEBUG, "AutoIncrement has closed")
    #
    #
    def __open_connection(self):
        return assure_not_null(self.__connector.rewind().connect(pinging=False, retrying=False))
    #
    def __gen_absolute_key(self, label):
        if label:
            return self.__default_key + ':' + str(label)
        return self.__default_key
Exemplo n.º 3
0
class SettingPublisher(object):
    #
    def __init__(self, *args, connector=None, **kwargs):
        if isinstance(connector, RedisClient):
            self.__use_shared_connector = True
            self.__connector = connector
        else:
            self.__use_shared_connector = False
            self.__connector = RedisClient(**kwargs)
        #
        self.CHANNEL_PREFIX = self.__connector.CHANNEL_GROUP + ':'
        #
        super(SettingPublisher, self).__init__()

    #
    ##
    @property
    def connector(self):
        return self.__connector

    #
    ##
    def publish(self,
                message: Union[Dict, bytes, str, int, float],
                label: Optional[Union[bytes, str]] = None,
                with_datetime: Optional[bool] = False,
                raise_on_error: Optional[bool] = False) -> Optional[Exception]:
        try:
            self.__publish_or_error(message,
                                    label=label,
                                    with_datetime=with_datetime)
            return None
        except Exception as err:
            if raise_on_error:
                raise err
            return err

    #
    #
    def __publish_or_error(self, message, label=None, with_datetime=False):
        if label is None:
            channel_name = self.__connector.CHANNEL_GROUP
        else:
            if isinstance(label, bytes):
                label = label.decode('utf-8')
            else:
                label = str(label)
            channel_name = self.CHANNEL_PREFIX + label
        #
        if isinstance(message, (dict, list)):
            message, err = json_dumps(message, with_datetime=with_datetime)
            if err:
                if LOG.isEnabledFor(logging.ERROR):
                    LOG.log(logging.ERROR, err)
                raise err
        elif not self.__is_valid_type(message):
            errmsg = "Invalid type of input: '%s'. Only a dict, list, bytes, string, int or float accepted." % type(
                message)
            if LOG.isEnabledFor(logging.ERROR):
                LOG.log(logging.ERROR, errmsg)
            raise ValueError(errmsg)
        #
        if LOG.isEnabledFor(logging.DEBUG):
            LOG.log(logging.DEBUG, "publish() a message [%s] to channel [%s]",
                    str(message), channel_name)
        #
        self.__open_connection().publish(channel_name, message)

    #
    #
    def close(self):
        if not self.__use_shared_connector:
            self.__connector.close()
        if LOG.isEnabledFor(logging.DEBUG):
            LOG.log(logging.DEBUG, "SettingPublisher has closed")

    #
    #
    def __open_connection(self):
        return assure_not_null(self.__connector.rewind().connect(
            pinging=False, retrying=False))

    #
    #
    @staticmethod
    def __is_valid_type(data):
        return isinstance(data,
                          (bytes, str, float)) or (isinstance(data, int) and
                                                   (type(data) != type(True)))