Managing WebSocket messages concurrently with detached actions
When using Django Channels, WebSocket consumers handle one message at a time for each connection. This means long-running async tasks block the consumer from processing other messages.
With Django Channels Rest Framework, you can run actions in a detached manner, allowing your consumer to handle other messages concurrently.
To enable this, add detached=True
to your @action
method decorator:
from djangochannelsrestframework.decorators import action
from djangochannelsrestframework.consumers import AsyncAPIConsumer
class MyConsumer(AsyncAPIConsumer):
@action(detached=True)
async def send_email(self, pk=None, to=None, **kwargs):
# Perform long-running async tasks like making network requests
Detached actions are essential for handling long-running async operations, such as upstream network requests. Without them, your consumer will queue all incoming messages until the current action finishes.