1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
|
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause
"""Integrate Huey tasks with Flask application contexts."""
from collections.abc import Callable
from functools import update_wrapper, wraps
from typing import Any
from urllib.parse import SplitResult, urlsplit, urlunsplit
from flask import Flask
from huey import Huey as BaseHuey
from huey.api import TaskWrapper
from .json_serializer import TaggedJSONSerializer
class _DeferredTask:
"""Stable public task handle which follows the extension's current backend.
Huey creates task classes and registers them when its decorator is applied.
Keep that backend-specific TaskWrapper private, so imported task handles can
be used across Flask app factories without referring to an obsolete queue.
"""
def __init__(
self,
extension: FlaskHuey,
func: Callable[..., Any],
args: tuple[Any, ...],
kwargs: dict[str, Any],
*,
periodic: bool,
) -> None:
self._extension = extension
self._func = func
self._args = args
self._kwargs = kwargs
self._periodic = periodic
self._registered: TaskWrapper | None = None
update_wrapper(self, func)
def bind(self) -> None:
"""Bind the original function to the latest initialized backend.
Register the task decorator again so its stable handle uses the currently
initialized Huey instance.
"""
backend = self._extension.huey
decorator = backend.periodic_task if self._periodic else backend.task
self._registered = decorator(*self._args, **self._kwargs)(
self._extension._with_app_context(self._func)
)
def _bound_task(self) -> TaskWrapper:
if self._registered is None:
raise RuntimeError(
"Huey has not been initialized. Call huey.init_app(app) first."
)
return self._registered
def __call__(self, *args: Any, **kwargs: Any) -> Any:
"""Enqueue a task using the active backend.
:param args: Positional arguments passed to the queued task.
:param kwargs: Keyword arguments passed to the queued task.
:returns: Result of enqueueing the task on the current backend.
"""
return self._bound_task()(*args, **kwargs)
def __getattr__(self, name: str) -> Any:
"""Delegate Huey task operations (call_local, schedule, s, etc.).
:param name: Huey task attribute to delegate.
:returns: Requested attribute of the currently bound Huey task.
"""
return getattr(self._bound_task(), name)
class FlaskHuey:
"""Provide Flask integration for a Huey instance.
The extension initializes a Huey backend from the Flask configuration and
wraps tasks so that they execute within an application context.
"""
def __init__(self, app: Flask | None = None) -> None:
"""Initialize the Huey extension.
:param app: Flask application to initialize immediately, if provided.
"""
self.app: Flask | None = None
self._huey: BaseHuey | None = None
self._task_handles: list[_DeferredTask] = []
if app is not None:
self.init_app(app)
def init_app(self, app: Flask) -> None:
"""Initialize Huey for a Flask application.
The backend and its storage options are derived from ``HUEY_URL`` and the
resulting extension is registered with the application.
:param app: Flask application to initialize.
:raises RuntimeError: If the configured Huey backend URL is invalid or uses an
unsupported scheme.
"""
config: dict[str, Any] = {
"name": app.import_name,
"results": True,
"store_none": False,
"utc": True,
"immediate": app.config.get("TESTING", False),
**app.config.get("HUEY", {}),
}
# An arbitrary serializer supplied via HUEY would silently restore
# pickle deserialization of broker-controlled bytes. Fail closed.
if "serializer" in config:
raise RuntimeError(
"HUEY.serializer cannot be overridden; JSON is required."
)
config["serializer"] = TaggedJSONSerializer(
compression=config.pop("compression", False),
use_zlib=config.pop("use_zlib", False),
)
url = app.config.get("HUEY_URL", config.pop("url", "memory://"))
huey_class, storage_kwargs = self.backend_from_url(url)
self.app = app
self._huey = huey_class(**config, **storage_kwargs)
# Import order is immaterial: tasks declared before initialization are
# registered now, and previously imported handles follow this backend.
for task in self._task_handles:
task.bind()
app.extensions["huey"] = self
@property
def huey(self) -> BaseHuey:
"""Return the initialized Huey instance.
:returns: Active, initialized Huey backend.
:raises RuntimeError: If the extension has not been initialized.
"""
if self._huey is None:
raise RuntimeError(
"Huey has not been initialized. "
"Call huey.init_app(app) before using tasks."
)
return self._huey
def _with_app_context[**P, R](self, func: Callable[P, R]) -> Callable[P, R]:
"""Return a task wrapper that executes with the configured Flask app.
:param func: Task function to wrap in a Flask application context.
:returns: Task wrapper that enters the configured Flask application context.
:raises RuntimeError: If no Flask application has been registered.
"""
@wraps(func)
def wrapped(*args: P.args, **kwargs: P.kwargs) -> R:
if self.app is None:
raise RuntimeError("Flask app is not available.")
with self.app.app_context():
return func(*args, **kwargs)
return wrapped
def _register_task[**P, R](
self,
func: Callable[P, R],
task_args: tuple[Any, ...],
task_kwargs: dict[str, Any],
*,
periodic: bool,
) -> _DeferredTask:
handle = _DeferredTask(self, func, task_args, task_kwargs, periodic=periodic)
self._task_handles.append(handle)
if self._huey is not None:
handle.bind()
return handle
def task[**P, R](
self, *task_args: Any, **task_kwargs: Any
) -> Callable[[Callable[P, R]], _DeferredTask]:
"""Declare a task even before :meth:`init_app` has run.
:param task_args: Positional arguments for the Huey task decorator.
:param task_kwargs: Keyword options for the Huey task decorator.
:returns: Decorator that registers and returns a lazily bound task.
"""
def decorator(func: Callable[P, R]) -> _DeferredTask:
return self._register_task(func, task_args, task_kwargs, periodic=False)
return decorator
def periodic_task[**P, R](
self, *task_args: Any, **task_kwargs: Any
) -> Callable[[Callable[P, R]], _DeferredTask]:
"""Declare a periodic task against the current or next backend.
:param task_args: Positional arguments for the Huey periodic-task decorator.
:param task_kwargs: Keyword options for the Huey periodic-task decorator.
:returns: Decorator that registers and returns a lazily bound periodic task.
"""
def decorator(func: Callable[P, R]) -> _DeferredTask:
return self._register_task(func, task_args, task_kwargs, periodic=True)
return decorator
def __getattr__(self, name: str) -> Any:
"""Forward an unknown attribute to the underlying Huey instance.
:param name: Name of the attribute to retrieve.
:returns: Attribute from the initialized Huey instance.
:raises RuntimeError: If the extension has not been initialized.
"""
return getattr(self.huey, name)
@staticmethod
def backend_from_url(url: str) -> tuple[type[BaseHuey], dict[str, Any]]:
"""Determine the Huey backend and storage options from a URL.
:param url: Huey backend URL. SQLite and file paths use SQLAlchemy's slash
convention: three slashes for relative paths and four for absolute
paths (not RFC 8089 file-URI semantics).
:returns: Huey backend class and keyword arguments for its storage backend.
:raises RuntimeError: If the URL is malformed for the selected backend or uses
an unsupported scheme.
"""
parsed = urlsplit(url)
scheme = parsed.scheme.lower()
if scheme.partition("+")[0] in {"redis", "rediss"}:
return _redis_class_and_options(parsed)
if scheme in {"sqlite", "file"}:
return _file_class_and_options(url, scheme)
if scheme in {"postgres", "postgresql"}:
from huey import PostgresHuey
return PostgresHuey, {"dsn": url}
if scheme == "memory":
from huey import MemoryHuey
return MemoryHuey, {}
if scheme == "blackhole":
from huey import BlackHoleHuey
return BlackHoleHuey, {}
raise RuntimeError(f"Unsupported HUEY_URL scheme: {scheme!r}")
def _redis_class_and_options(
parsed: SplitResult,
) -> tuple[type[BaseHuey], dict[str, Any]]:
"""Select a Redis Huey flavour while retaining the underlying URL scheme.
:param parsed: Parsed Redis backend URL, including any flavour suffix.
:returns: Huey class and constructor options for the requested Redis flavour.
:raises RuntimeError: If the Redis backend flavour is unsupported.
"""
from huey import (
PriorityRedisExpireHuey,
PriorityRedisHuey,
RedisExpireHuey,
RedisHuey,
)
scheme = parsed.scheme.lower()
base_scheme, separator, flavour = scheme.partition("+")
backends = {
"": RedisHuey,
"priority": PriorityRedisHuey,
"expire": RedisExpireHuey,
"priority+expire": PriorityRedisExpireHuey,
}
if flavour not in backends or (separator and not flavour):
raise RuntimeError(f"Unsupported HUEY_URL scheme: {scheme!r}")
fixed_url = urlunsplit(parsed._replace(scheme=base_scheme))
return backends[flavour], {"url": fixed_url}
def _file_class_and_options(
url: str, scheme: str
) -> tuple[type[BaseHuey], dict[str, Any]]:
"""Extract a relative or absolute SQLite/file storage path.
:param url: Backend URL containing the storage filename or path.
:param scheme: Selected file or SQLite backend scheme.
:returns: Huey class and constructor options for the file-backed queue.
:raises RuntimeError: If the storage URL is malformed or omits the path.
"""
from huey import FileHuey, SqliteHuey
if scheme == "sqlite":
backend, option, description, example = (
SqliteHuey,
"filename",
"SQLite Huey",
"sqlite:///huey.db (relative) or sqlite:////var/huey.db (absolute)",
)
missing = "SQLite Huey URL must include a database path."
else:
backend, option, description, example = (
FileHuey,
"path",
"File Huey",
"file:///huey-queue (relative) or file:////var/huey-queue (absolute)",
)
missing = "File Huey URL must include a directory path."
prefix = f"{scheme}:///"
if not url.startswith(prefix):
raise RuntimeError(f"{description} URLs must look like {example}")
# Four slashes retain the initial '/' of an absolute path; three do not.
path = url.removeprefix(prefix)
if not path:
raise RuntimeError(missing)
return backend, {option: path}
|