I was trying to copy the tutorial in Django Channels Documentation. But I'm having errors. It says
You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly.
INFO WebSocket HANDSHAKING /ws/notifications/app/98578113-89e9-4465-ab37-e8b4d89450c2/ [127.0.0.1:57302]
Exception inside application: You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly.
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/consumer.py", line 59, in call [receive, self.channel_receive], self.dispatch
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/consumer.py", line 73, in dispatch await handler(message)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/generic/websocket.py", line 175, in websocket_connect await self.connect()
File "/Users/goutambseervi/PycharmProjects/cilliai-backend/api/notifications/consumers.py", line 51, in connect self.channel_name
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/asgiref/sync.py", line 62, in call "You cannot use AsyncToSync in the same thread as an async event loop - "
You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly.
Here is the consumer:
class AppConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['user_id']
self.room_group_name = 'chat_%s' % self.room_name
await async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, code):
await async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
async def receive(self, text_data=None, bytes_data=None):
text_data_json = json.loads(text_data)
message = text_data_json['message']
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)
async def send_message(self, event):
message = event['message']
await self.send(text_data=json.dumps({
'message': message
}))