Skip to content

SyncRedisGlobalConfig

Sync Redis Global Config.

SyncRedisGlobalConfig

Bases: BaseGlobalConfig[Literal[False]], SyncPluginMixin

Global Config running through Redis and working with global values.

Example

from qtasks import QueueTasks
from qtasks.configs import SyncRedisGlobalConfig
from qtasks.storage import SyncRedisStorage
from qtasks.brokers import SyncRedisBroker

global_config = SyncRedisGlobalConfig(name="QueueTasks", url="redis://localhost:6379/2")

storage = SyncRedisStorage(name="QueueTasks", global_config=global_config, url="redis://localhost:6379/2")

broker = SyncRedisBroker(name="QueueTasks", storage=storage, url="redis://localhost:6379/2")

app = QueueTasks(broker=broker)
Source code in src/qtasks/configs/sync_redisglobalconfig.py
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
class SyncRedisGlobalConfig(BaseGlobalConfig[Literal[False]], SyncPluginMixin):
    """
    Global Config running through Redis and working with global values.

    ## Example

    ```python
    from qtasks import QueueTasks
    from qtasks.configs import SyncRedisGlobalConfig
    from qtasks.storage import SyncRedisStorage
    from qtasks.brokers import SyncRedisBroker

    global_config = SyncRedisGlobalConfig(name="QueueTasks", url="redis://localhost:6379/2")

    storage = SyncRedisStorage(name="QueueTasks", global_config=global_config, url="redis://localhost:6379/2")

    broker = SyncRedisBroker(name="QueueTasks", storage=storage, url="redis://localhost:6379/2")

    app = QueueTasks(broker=broker)
    ```
    """

    def __init__(
        self,
        name: Annotated[
            str,
            Doc("""
                    Project name. This name is also used by the broker.

                    Default: `QueueTasks`.
                    """),
        ] = "QueueTasks",
        url: Annotated[
            str,
            Doc("""
                    URL to connect to Redis.

                    Default: `redis://localhost:6379/0`.
                    """),
        ] = "redis://localhost:6379/0",
        redis_connect: Annotated[
            redis.Redis | None,
            Doc("""
                    External connection class to Redis.

                    Default: `None`.
                    """),
        ] = None,
        config_name: Annotated[
            str | None,
            Doc("""
                    Folder name with Hash. The name is updated to: `name:queue_name`.

                    Default: `name:GlobalConfig`.
                    """),
        ] = None,
        log: Annotated[
            Logger | None,
            Doc("""
                    Logger.

                    Default: `qtasks.logs.Logger`.
                    """),
        ] = None,
        config: Annotated[
            QueueConfig | None,
            Doc("""
                    Config.

                    Default: `qtasks.configs.config.QueueConfig`.
                    """),
        ] = None,
        events: Annotated[
            Optional[BaseEvents],
            Doc("""
                    Events.

                    Default: `qtasks.events.SyncEvents`.
                    """),
        ] = None,
    ):
        """
        Initializing the Redis global config.

        Args:
            name (str, optional): Project name. Default: `QueueTasks`.
            url (str, optional): URL to connect to Redis. Default: `redis://localhost:6379/0`.
            redis_connect (redis.Redis, optional): External Redis connection class. Default: None.
            config_name (str, optional): Name of the Hash Folder. Default: `None`.
            log (Logger, optional): Logger. Default: `None`.
            config (QueueConfig, optional): Configuration. Default: `None`.
            events (BaseEvents, optional): Events. Default: `qtasks.events.SyncEvents`.
        """
        super().__init__(name=name, log=log, config=config, events=events)
        self.name = name
        self.url = url
        self.config_name = f"{self.name}:{config_name or 'GlobalConfig'}"
        self.events = self.events or SyncEvents()

        self.client = redis_connect or redis.from_url(
            self.url, decode_responses=True, encoding="utf-8"
        )
        self.running = False

    def set(self, name: str, key: str, value: str) -> None:
        """
        Add new value.

        Args:
            name (str): Name.
            key (str): Key.
            value(str): Value.
        """
        new_data = self._plugin_trigger(
            "global_config_set",
            global_config=self,
            name_=name,
            key=key,
            value=value,
            return_last=True,
        )
        if new_data:
            name = new_data.get("name", name)
            key = new_data.get("key", key)
            value = new_data.get("value", value)

        self.client.hset(name=f"{self.config_name}:{name}", key=key, value=value)
        return

    def get(self, key: str, name: str) -> Any:
        """
        Get value.

        Args:
            key (str): Key.
            name (str): Name.

        Returns:
            Any: Value.
        """
        result = self.client.hget(name=f"{self.config_name}:{key}", key=name)
        new_result = self._plugin_trigger(
            "global_config_get", global_config=self, get=result, return_last=True
        )
        if new_result:
            result = new_result.get("get", result)
        return result

    def get_all(self, key: str) -> dict[str, Any]:
        """
        Get all values.

        Args:
            key (str): Key.

        Returns:
            Dict[str, Any]: Values.
        """
        raw = self.client.hgetall(name=f"{self.config_name}:{key}")
        result = cast(dict, raw)
        new_result = self._plugin_trigger(
            "global_config_get_all", global_config=self, get=result, return_last=True
        )
        if new_result:
            result = new_result.get("get", result)
        return result

    def get_match(self, match: str) -> Any | dict:
        """
        Get value by pattern.

        Args:
            match (str): Pattern.

        Returns:
            Any | Dict[str, Any]: Value or Values.
        """
        self.config_name: str
        result = self.client.hscan(self.config_name, match=match)
        new_result = self._plugin_trigger(
            "global_config_get_match", global_config=self, get=result, return_last=True
        )
        if new_result:
            result = new_result.get("get", result)
        return result

    def start(self) -> None:
        """Launching the Broker. This function is enabled by the main instance of `QueueTasks` via `run_forever."""
        self._plugin_trigger("global_config_start", global_config=self)
        self.running = True
        global_config = GlobalConfigSchema(name=self.name, status="running")
        self.client.hset(
            name=f"{self.config_name}:main", mapping=global_config.__dict__
        )
        Thread(target=self._set_status, daemon=True).start()

    def stop(self) -> None:
        """Stops Global Config. This function is invoked by the main `QueueTasks` instance after the `run_forever` function completes."""
        self._plugin_trigger("global_config_stop", global_config=self)
        self.running = False
        self.client.close()
        return

    def _set_status(self):
        """Updates the startup status of the global config."""
        self._plugin_trigger("global_config_set_status", global_config=self)
        ttl = self.config.global_config_status_ttl
        interval = self.config.global_config_status_set_periodic
        while self.running:
            self.client.expire(f"{self.config_name}:main", ttl)
            time.sleep(interval)

__init__(name='QueueTasks', url='redis://localhost:6379/0', redis_connect=None, config_name=None, log=None, config=None, events=None)

Initializing the Redis global config.

Parameters:

Name Type Description Default
name str

Project name. Default: QueueTasks.

'QueueTasks'
url str

URL to connect to Redis. Default: redis://localhost:6379/0.

'redis://localhost:6379/0'
redis_connect Redis

External Redis connection class. Default: None.

None
config_name str

Name of the Hash Folder. Default: None.

None
log Logger

Logger. Default: None.

None
config QueueConfig

Configuration. Default: None.

None
events BaseEvents

Events. Default: qtasks.events.SyncEvents.

None
Source code in src/qtasks/configs/sync_redisglobalconfig.py
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def __init__(
    self,
    name: Annotated[
        str,
        Doc("""
                Project name. This name is also used by the broker.

                Default: `QueueTasks`.
                """),
    ] = "QueueTasks",
    url: Annotated[
        str,
        Doc("""
                URL to connect to Redis.

                Default: `redis://localhost:6379/0`.
                """),
    ] = "redis://localhost:6379/0",
    redis_connect: Annotated[
        redis.Redis | None,
        Doc("""
                External connection class to Redis.

                Default: `None`.
                """),
    ] = None,
    config_name: Annotated[
        str | None,
        Doc("""
                Folder name with Hash. The name is updated to: `name:queue_name`.

                Default: `name:GlobalConfig`.
                """),
    ] = None,
    log: Annotated[
        Logger | None,
        Doc("""
                Logger.

                Default: `qtasks.logs.Logger`.
                """),
    ] = None,
    config: Annotated[
        QueueConfig | None,
        Doc("""
                Config.

                Default: `qtasks.configs.config.QueueConfig`.
                """),
    ] = None,
    events: Annotated[
        Optional[BaseEvents],
        Doc("""
                Events.

                Default: `qtasks.events.SyncEvents`.
                """),
    ] = None,
):
    """
    Initializing the Redis global config.

    Args:
        name (str, optional): Project name. Default: `QueueTasks`.
        url (str, optional): URL to connect to Redis. Default: `redis://localhost:6379/0`.
        redis_connect (redis.Redis, optional): External Redis connection class. Default: None.
        config_name (str, optional): Name of the Hash Folder. Default: `None`.
        log (Logger, optional): Logger. Default: `None`.
        config (QueueConfig, optional): Configuration. Default: `None`.
        events (BaseEvents, optional): Events. Default: `qtasks.events.SyncEvents`.
    """
    super().__init__(name=name, log=log, config=config, events=events)
    self.name = name
    self.url = url
    self.config_name = f"{self.name}:{config_name or 'GlobalConfig'}"
    self.events = self.events or SyncEvents()

    self.client = redis_connect or redis.from_url(
        self.url, decode_responses=True, encoding="utf-8"
    )
    self.running = False

get(key, name)

Get value.

Parameters:

Name Type Description Default
key str

Key.

required
name str

Name.

required

Returns:

Name Type Description
Any Any

Value.

Source code in src/qtasks/configs/sync_redisglobalconfig.py
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def get(self, key: str, name: str) -> Any:
    """
    Get value.

    Args:
        key (str): Key.
        name (str): Name.

    Returns:
        Any: Value.
    """
    result = self.client.hget(name=f"{self.config_name}:{key}", key=name)
    new_result = self._plugin_trigger(
        "global_config_get", global_config=self, get=result, return_last=True
    )
    if new_result:
        result = new_result.get("get", result)
    return result

get_all(key)

Get all values.

Parameters:

Name Type Description Default
key str

Key.

required

Returns:

Type Description
dict[str, Any]

Dict[str, Any]: Values.

Source code in src/qtasks/configs/sync_redisglobalconfig.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
def get_all(self, key: str) -> dict[str, Any]:
    """
    Get all values.

    Args:
        key (str): Key.

    Returns:
        Dict[str, Any]: Values.
    """
    raw = self.client.hgetall(name=f"{self.config_name}:{key}")
    result = cast(dict, raw)
    new_result = self._plugin_trigger(
        "global_config_get_all", global_config=self, get=result, return_last=True
    )
    if new_result:
        result = new_result.get("get", result)
    return result

get_match(match)

Get value by pattern.

Parameters:

Name Type Description Default
match str

Pattern.

required

Returns:

Type Description
Any | dict

Any | Dict[str, Any]: Value or Values.

Source code in src/qtasks/configs/sync_redisglobalconfig.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def get_match(self, match: str) -> Any | dict:
    """
    Get value by pattern.

    Args:
        match (str): Pattern.

    Returns:
        Any | Dict[str, Any]: Value or Values.
    """
    self.config_name: str
    result = self.client.hscan(self.config_name, match=match)
    new_result = self._plugin_trigger(
        "global_config_get_match", global_config=self, get=result, return_last=True
    )
    if new_result:
        result = new_result.get("get", result)
    return result

set(name, key, value)

Add new value.

Parameters:

Name Type Description Default
name str

Name.

required
key str

Key.

required
value str

Value.

required
Source code in src/qtasks/configs/sync_redisglobalconfig.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def set(self, name: str, key: str, value: str) -> None:
    """
    Add new value.

    Args:
        name (str): Name.
        key (str): Key.
        value(str): Value.
    """
    new_data = self._plugin_trigger(
        "global_config_set",
        global_config=self,
        name_=name,
        key=key,
        value=value,
        return_last=True,
    )
    if new_data:
        name = new_data.get("name", name)
        key = new_data.get("key", key)
        value = new_data.get("value", value)

    self.client.hset(name=f"{self.config_name}:{name}", key=key, value=value)
    return

start()

Launching the Broker. This function is enabled by the main instance of QueueTasks via `run_forever.

Source code in src/qtasks/configs/sync_redisglobalconfig.py
209
210
211
212
213
214
215
216
217
def start(self) -> None:
    """Launching the Broker. This function is enabled by the main instance of `QueueTasks` via `run_forever."""
    self._plugin_trigger("global_config_start", global_config=self)
    self.running = True
    global_config = GlobalConfigSchema(name=self.name, status="running")
    self.client.hset(
        name=f"{self.config_name}:main", mapping=global_config.__dict__
    )
    Thread(target=self._set_status, daemon=True).start()

stop()

Stops Global Config. This function is invoked by the main QueueTasks instance after the run_forever function completes.

Source code in src/qtasks/configs/sync_redisglobalconfig.py
219
220
221
222
223
224
def stop(self) -> None:
    """Stops Global Config. This function is invoked by the main `QueueTasks` instance after the `run_forever` function completes."""
    self._plugin_trigger("global_config_stop", global_config=self)
    self.running = False
    self.client.close()
    return