| 1 |
Events |
| 2 |
====== |
| 3 |
|
| 4 |
Litestar supports a simple implementation of the event emitter / listener pattern: |
| 5 |
|
| 6 |
.. code-block:: python |
| 7 |
|
| 8 |
from dataclasses import dataclass |
| 9 |
|
| 10 |
from litestar import Request, post |
| 11 |
from litestar.events import listener |
| 12 |
from litestar import Litestar |
| 13 |
|
| 14 |
from db import user_repository |
| 15 |
from utils.email import send_welcome_mail |
| 16 |
|
| 17 |
|
| 18 |
@listener("user_created") |
| 19 |
async def send_welcome_email_handler(email: str) -> None: |
| 20 |
# do something here to send an email |
| 21 |
await send_welcome_mail(email) |
| 22 |
|
| 23 |
|
| 24 |
@dataclass |
| 25 |
class CreateUserDTO: |
| 26 |
first_name: str |
| 27 |
last_name: str |
| 28 |
email: str |
| 29 |
|
| 30 |
|
| 31 |
@post("/users") |
| 32 |
async def create_user_handler(data: UserDTO, request: Request) -> None: |
| 33 |
# do something here to create a new user |
| 34 |
# e.g. insert the user into a database |
| 35 |
await user_repository.insert(data) |
| 36 |
|
| 37 |
# assuming we have now inserted a user, we want to send a welcome email. |
| 38 |
# To do this in a none-blocking fashion, we will emit an event to a listener, which will send the email, |
| 39 |
# using a different async block than the one where we are returning a response. |
| 40 |
request.app.emit("user_created", email=data.email) |
| 41 |
|
| 42 |
|
| 43 |
app = Litestar( |
| 44 |
route_handlers=[create_user_handler], listeners=[send_welcome_email_handler] |
| 45 |
) |
| 46 |
|
| 47 |
|
| 48 |
The above example illustrates the power of this pattern - it allows us to perform async operations without blocking, |
| 49 |
and without slowing down the response cycle. |
| 50 |
|
| 51 |
Listening to Multiple Events |
| 52 |
++++++++++++++++++++++++++++ |
| 53 |
|
| 54 |
Event listeners can listen to multiple events: |
| 55 |
|
| 56 |
.. code-block:: python |
| 57 |
|
| 58 |
from litestar.events import listener |
| 59 |
|
| 60 |
|
| 61 |
@listener("user_created", "password_changed") |
| 62 |
async def send_email_handler(email: str, message: str) -> None: |
| 63 |
# do something here to send an email |
| 64 |
|
| 65 |
await send_email(email, message) |
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
Using Multiple Listeners |
| 71 |
++++++++++++++++++++++++ |
| 72 |
|
| 73 |
You can also listen to the same events using multiple listeners: |
| 74 |
|
| 75 |
.. code-block:: python |
| 76 |
|
| 77 |
from uuid import UUID |
| 78 |
from dataclasses import dataclass |
| 79 |
|
| 80 |
from litestar import Request, post |
| 81 |
from litestar.events import listener |
| 82 |
|
| 83 |
from db import user_repository |
| 84 |
from utils.client import client |
| 85 |
from utils.email import send_farewell_email |
| 86 |
|
| 87 |
|
| 88 |
@listener("user_deleted") |
| 89 |
async def send_farewell_email_handler(email: str, **kwargs) -> None: |
| 90 |
# do something here to send an email |
| 91 |
await send_farewell_email(email) |
| 92 |
|
| 93 |
|
| 94 |
@listener("user_deleted") |
| 95 |
async def notify_customer_support(reason: str, **kwargs) -> None: |
| 96 |
# do something here to send an email |
| 97 |
await client.post("some-url", reason) |
| 98 |
|
| 99 |
|
| 100 |
@dataclass |
| 101 |
class DeleteUserDTO: |
| 102 |
email: str |
| 103 |
reason: str |
| 104 |
|
| 105 |
|
| 106 |
@post("/users") |
| 107 |
async def delete_user_handler(data: UserDTO, request: Request) -> None: |
| 108 |
await user_repository.delete({"email": email}) |
| 109 |
request.app.emit("user_deleted", email=data.email, reason="deleted") |
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
In the above example we are performing two side effect for the same event, one sends the user an email, and the other |
| 114 |
sending an HTTP request to a service management system to create an issue. |
| 115 |
|
| 116 |
Passing Arguments to Listeners |
| 117 |
++++++++++++++++++++++++++++++ |
| 118 |
|
| 119 |
The method :meth:`emit <litestar.events.BaseEventEmitterBackend.emit>` has the following signature: |
| 120 |
|
| 121 |
.. code-block:: python |
| 122 |
|
| 123 |
def emit(self, event_id: str, *args: Any, **kwargs: Any) -> None: ... |
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
This means that it expects a string for ``event_id`` following by any number of positional and keyword arguments. While |
| 128 |
this is highly flexible, it also means you need to ensure the listeners for a given event can handle all the expected args |
| 129 |
and kwargs. |
| 130 |
|
| 131 |
For example, the following would raise an exception in python: |
| 132 |
|
| 133 |
.. code-block:: python |
| 134 |
|
| 135 |
@listener("user_deleted") |
| 136 |
async def send_farewell_email_handler(email: str) -> None: |
| 137 |
await send_farewell_email(email) |
| 138 |
|
| 139 |
|
| 140 |
@listener("user_deleted") |
| 141 |
async def notify_customer_support(reason: str) -> None: |
| 142 |
# do something here to send an email |
| 143 |
await client.post("some-url", reason) |
| 144 |
|
| 145 |
|
| 146 |
@dataclass |
| 147 |
class DeleteUserDTO: |
| 148 |
email: str |
| 149 |
reason: str |
| 150 |
|
| 151 |
|
| 152 |
@post("/users") |
| 153 |
async def delete_user_handler(data: UserDTO, request: Request) -> None: |
| 154 |
await user_repository.delete({"email": email}) |
| 155 |
request.app.emit("user_deleted", email=data.email, reason="deleted") |
| 156 |
|
| 157 |
|
| 158 |
|
| 159 |
The reason for this is that both listeners will receive two kwargs - ``email`` and ``reason``. To avoid this, the previous example |
| 160 |
had ``**kwargs`` in both: |
| 161 |
|
| 162 |
.. code-block:: python |
| 163 |
|
| 164 |
@listener("user_deleted") |
| 165 |
async def send_farewell_email_handler(email: str, **kwargs) -> None: |
| 166 |
await send_farewell_email(email) |
| 167 |
|
| 168 |
|
| 169 |
@listener("user_deleted") |
| 170 |
async def notify_customer_support(reason: str, **kwargs) -> None: |
| 171 |
await client.post("some-url", reason) |
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
Creating Event Emitters |
| 176 |
----------------------- |
| 177 |
|
| 178 |
An "event emitter" is a class that inherits from |
| 179 |
:class:`BaseEventEmitterBackend <litestar.events.BaseEventEmitterBackend>`, which |
| 180 |
itself inherits from :obj:`contextlib.AbstractAsyncContextManager`. |
| 181 |
|
| 182 |
- :meth:`emit <litestar.events.BaseEventEmitterBackend.emit>`: This is the method that performs the actual emitting |
| 183 |
logic. |
| 184 |
|
| 185 |
Additionally, the abstract ``__aenter__`` and ``__aexit__`` methods from |
| 186 |
:obj:`contextlib.AbstractAsyncContextManager` must be implemented, allowing the |
| 187 |
emitter to be used as an async context manager. |
| 188 |
|
| 189 |
By default Litestar uses the |
| 190 |
:class:`SimpleEventEmitter <litestar.events.SimpleEventEmitter>`, which offers an |
| 191 |
in-memory async queue. |
| 192 |
|
| 193 |
This solution works well if the system does not need to rely on complex behaviour, such as a retry |
| 194 |
mechanism, persistence, or scheduling/cron. For these more complex use cases, users should implement their own backend |
| 195 |
using either a DB/Key store that supports events (Redis, Postgres, etc.), or a message broker, job queue, or task queue |
| 196 |
technology. |