Repository navigation
Expand file tree
/
Copy path__init__.py
More file actions
72 lines (52 loc) · 2 KB
/
Copy path__init__.py
File metadata and controls
72 lines (52 loc) · 2 KB
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
"""Django integration. Requires the ``django`` extra:
pip install "babelqueue[django]"
Add ``"babelqueue.django"`` to ``INSTALLED_APPS`` and configure a ``BABELQUEUE``
settings dict::
BABELQUEUE = {
"broker_url": "redis://localhost:6379/0",
"queue": "orders",
"max_attempts": 3,
"dead_letter": True,
}
Then publish from views/signals with :func:`publish`, register handlers on
:func:`get_app`, and run the consumer with ``python manage.py babelqueue_worker``.
The runtime is the shared :class:`~babelqueue.BabelQueue`, so messages interoperate
with the PHP/Laravel, Go, Node, ... SDKs. ``django`` is imported lazily.
"""
from __future__ import annotations
from typing import Any, Dict, Mapping, Optional
from ..app import BabelQueue
# Keys (besides broker_url) forwarded to the BabelQueue constructor.
_APP_KWARGS = frozenset(
{
"queue",
"on_unknown_urn",
"max_attempts",
"dead_letter",
"dead_letter_queue",
"dead_letter_suffix",
"transport",
}
)
_app: Optional[BabelQueue] = None
def _build() -> BabelQueue:
from django.conf import settings # lazy
raw: Mapping[str, Any] = getattr(settings, "BABELQUEUE", {}) or {}
kwargs: Dict[str, Any] = {k: v for k, v in raw.items() if k in _APP_KWARGS}
broker = raw.get("broker_url", "memory://")
return BabelQueue(broker, **kwargs)
def get_app() -> BabelQueue:
"""Return the process-wide :class:`~babelqueue.BabelQueue`, built from
``settings.BABELQUEUE`` on first use."""
global _app
if _app is None:
_app = _build()
return _app
def publish(urn: str, data: Mapping[str, Any], **kwargs: Any) -> str:
"""Publish a message through the configured app; returns its id (``meta.id``)."""
return get_app().publish(urn, dict(data), **kwargs)
def reset() -> None:
"""Drop the cached app so the next :func:`get_app` rebuilds it (tests / settings reload)."""
global _app
_app = None
__all__ = ["get_app", "publish", "reset"]