Django 通道错误:您不能在与异步事件循环相同的线程中使用 AsyncToSync



我试图在 Django 频道文档中复制教程。但是我有错误。它说

您不能在与异步事件循环相同的线程中使用 AsyncToSync - 只需直接等待异步函数即可。

信息 WebSocket 握手/ws/notifications/app/98578113-89e9-4465-ab37-e8b4d89450c2/[127.0.0.1:57302]

应用程序内部异常:您不能在与异步事件循环相同的线程中使用 AsyncToSync - 只需直接等待异步函数即可。

文件 "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/consumer.py",第 59 行,incall[receive, self.channel_receive], self.dispatch

文件"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/utils.py",第 51 行,第 await_many_dispatch 行 等待发送(结果(

文件 "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/consumer.py",第 73 行,在调度中 等待处理程序(消息(

文件"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/generic/websocket.py",第 175 行,websocket_connect await self.connect((

文件 "/Users/goutambseervi/PycharmProjects/cilliai-backend/api/notifications/consumer.py",第 51 行,在连接中 self.channel_name

文件 "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/asgiref/sync.py",第 62 行,在调用中"您不能在与异步事件循环相同的线程中使用 AsyncToSync - ">

您不能在与异步事件循环相同的线程中使用 AsyncToSync - 只需直接等待异步函数即可。

这是消费者:

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
}))

我认为您需要替换此调用:

await async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
await async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)

有了这个,请等待:

await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)

最新更新