Skip to content

Commit d90af6c

Browse files
committed
Add wrapper for asend for signals in django pre-5.0
1 parent 20bd9ed commit d90af6c

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

channels/consumer.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import functools
22

3-
from asgiref.sync import async_to_sync
3+
from asgiref.sync import async_to_sync, sync_to_async
44

55
from . import DEFAULT_CHANNEL_LAYER
66
from .db import database_sync_to_async
@@ -10,6 +10,16 @@
1010
from .utils import await_many_dispatch
1111

1212

13+
async def _asend_wrapper(signal, **kwargs):
14+
"""
15+
Signal.asend was introduced in Django 5.0, thus a wrapper is needed for older versions.
16+
"""
17+
if hasattr(signal, "asend"):
18+
await signal.asend(**kwargs)
19+
else:
20+
await sync_to_async(signal.send)(**kwargs)
21+
22+
1323
def get_handler_name(message):
1424
"""
1525
Looks at a message, checks it has a sensible type, and returns the
@@ -63,15 +73,15 @@ async def __call__(self, scope, receive, send):
6373
await await_many_dispatch([receive], self.dispatch)
6474
except StopConsumer:
6575
# Exit cleanly
66-
await consumer_terminated.asend(sender=self.__class__)
76+
await _asend_wrapper(consumer_terminated, sender=self.__class__)
6777

6878
async def dispatch(self, message):
6979
"""
7080
Works out what to do with a message.
7181
"""
7282
handler = getattr(self, get_handler_name(message), None)
7383
if handler:
74-
await consumer_started.asend(sender=self.__class__)
84+
await _asend_wrapper(consumer_started, sender=self.__class__)
7585
await handler(message)
7686
else:
7787
raise ValueError("No handler for message type %s" % message["type"])

0 commit comments

Comments
 (0)