Skip to content

AsyncRedisGlobalConfig

Async Redis Global Config.

AsyncRedisGlobalConfig

Bases: BaseGlobalConfig[Literal[True]], AsyncPluginMixin

Global Config running through Redis and working with global values.

Example

from qtasks import QueueTasks
from qtasks.configs import AsyncRedisGlobalConfig
from qtasks.storage import AsyncRedisStorage
from qtasks.brokers import AsyncRedisBroker

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

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

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

app = QueueTasks(broker=broker)
Source code in src/qtasks/configs/async_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
234
235
236
237
238
239
240
241
242
class AsyncRedisGlobalConfig(BaseGlobalConfig[Literal[True]], AsyncPluginMixin):
    """
    Global Config running through Redis and working with global values.

    ## Example

    ```python
    from qtasks import QueueTasks
    from qtasks.configs import AsyncRedisGlobalConfig
    from qtasks.storage import AsyncRedisStorage
    from qtasks.brokers import AsyncRedisBroker

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

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

    broker = AsyncRedisBroker(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[
            aioredis.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.AsyncEvents`.
                    """),
        ] = None,
    ):
        """
        Initializing the asynchronous 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 (aioredis.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.AsyncEvents`.
        """
        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 AsyncEvents()

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

        self.status_event = None
        self.running = False

    async 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 = await 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)

        raw = self.client.hset(name=f"{self.config_name}:{name}", key=key, value=value)
        await cast(Awaitable[int], raw)
        return

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

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

        Returns:
            Any: Value.
        """
        raw = self.client.hget(name=f"{self.config_name}:{key}", key=name)
        result = await cast(Awaitable[str | None], raw)

        new_result = await 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

    async 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 = await cast(Awaitable[dict], raw)
        new_result = await 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

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

        Args:
            match (str): Pattern.

        Returns:
            Any | Dict[str, Any]: Value or Values.
        """
        self.config_name: str
        raw = self.client.hscan(self.config_name, match=match)
        result = await cast(Awaitable[Any], raw)
        new_result = await 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

    async def start(self) -> None:
        """Launching the Broker. This function is enabled by the main instance of `QueueTasks` via `run_forever."""
        await self._plugin_trigger("global_config_start", global_config=self)
        self.running = True
        loop = asyncio.get_running_loop()
        self.status_event = loop.create_task(self._set_status())
        global_config = GlobalConfigSchema(name=self.name, status="running")
        raw = self.client.hset(
            name=f"{self.config_name}:main", mapping=global_config.__dict__
        )
        await cast(Awaitable[int], raw)

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

    async def _set_status(self):
        """Updates the startup status of the global config."""
        await 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:
            await self.client.expire(f"{self.config_name}:main", ttl)
            await asyncio.sleep(interval)

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

Initializing the asynchronous 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.AsyncEvents.

None
Source code in src/qtasks/configs/async_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
126
127
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[
        aioredis.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.AsyncEvents`.
                """),
    ] = None,
):
    """
    Initializing the asynchronous 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 (aioredis.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.AsyncEvents`.
    """
    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 AsyncEvents()

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

    self.status_event = None
    self.running = False

get(key, name) async

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/async_redisglobalconfig.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
async def get(self, key: str, name: str) -> Any:
    """
    Get value.

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

    Returns:
        Any: Value.
    """
    raw = self.client.hget(name=f"{self.config_name}:{key}", key=name)
    result = await cast(Awaitable[str | None], raw)

    new_result = await 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) async

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/async_redisglobalconfig.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
async 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 = await cast(Awaitable[dict], raw)
    new_result = await 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) async

Get values ​​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/async_redisglobalconfig.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
async def get_match(self, match: str) -> Any | dict:
    """
    Get values ​​by pattern.

    Args:
        match (str): Pattern.

    Returns:
        Any | Dict[str, Any]: Value or Values.
    """
    self.config_name: str
    raw = self.client.hscan(self.config_name, match=match)
    result = await cast(Awaitable[Any], raw)
    new_result = await 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) async

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/async_redisglobalconfig.py
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
async 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 = await 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)

    raw = self.client.hset(name=f"{self.config_name}:{name}", key=key, value=value)
    await cast(Awaitable[int], raw)
    return

start() async

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

Source code in src/qtasks/configs/async_redisglobalconfig.py
215
216
217
218
219
220
221
222
223
224
225
async def start(self) -> None:
    """Launching the Broker. This function is enabled by the main instance of `QueueTasks` via `run_forever."""
    await self._plugin_trigger("global_config_start", global_config=self)
    self.running = True
    loop = asyncio.get_running_loop()
    self.status_event = loop.create_task(self._set_status())
    global_config = GlobalConfigSchema(name=self.name, status="running")
    raw = self.client.hset(
        name=f"{self.config_name}:main", mapping=global_config.__dict__
    )
    await cast(Awaitable[int], raw)

stop() async

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

Source code in src/qtasks/configs/async_redisglobalconfig.py
227
228
229
230
231
232
233
async def stop(self) -> None:
    """Stops Global Config. This function is invoked by the main `QueueTasks` instance after the `run_forever` function completes."""
    await self._plugin_trigger("global_config_stop", global_config=self)
    self.running = False
    if self.status_event:
        self.status_event.cancel()
    await self.client.aclose()