我试图复制Django Channels Documentation中的教程。但是我有错误。它说
您不能在与异步事件循环相同的线程中使用AsyncToSync,而只能直接等待异步功能。
INFO 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行 [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中 等待self.connect()
文件“ /Users/goutambseervi/PycharmProjects/cilliai-backend/api/notifications/consumers.py”,第51行,在connect中 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
}))