python / intermediate
Snippet
Triggering Asynchronous Signal Handlers in Django using asend
Django signals support async handlers when dispatched using the asend method. This method awaits all connected receivers concurrently or sequentially depending on signal configuration, allowing async tasks to run natively without blocking event loops.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import asynciofrom django.dispatch import Signaluser_registered = Signal()async def notify_admin(sender, **kwargs):await asyncio.sleep(0.1)print(f"Async notification sent for user: {kwargs.get('username')}")user_registered.connect(notify_admin)async def main():await user_registered.asend(sender=None, username="alex")asyncio.run(main())
django
Breakdown
1
user_registered = Signal()
Instantiates a custom Django Signal object.
2
async def notify_admin(sender, **kwargs):
Defines an asynchronous receiver function capable of using await inside its body.
3
user_registered.connect(notify_admin)
Attaches the asynchronous function as a listener to the signal.
4
await user_registered.asend(sender=None, username="alex")
Dispatches the signal asynchronously using asend, passing keyword parameters to receivers.