gpt4 book ai didi

python - 信号和 django channel 聊天室

转载 作者:太空宇宙 更新时间:2023-11-04 04:42:41 25 4
gpt4 key购买 nike

嗨,我正在努力让两件事同时工作......

channels2 chat room例子可以开始,但我想添加一个功能,知道房间里有多少人。我通过更新房间模型来做到这一点。

然后我想要一个仪表板来显示当前最受欢迎的房间,我想再次使用 channel 进行更新。我使用了 django 信号方法,这种方法可以在没有人使用聊天时更新模型。

但是,当有人加入聊天时查看仪表板是否更新时出现错误。

    2018-05-11 19:19:09,634 - ERROR - server - Exception inside application: You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly.
File "/dev/channels_sk/channels-master/channels/consumer.py", line 54, in __call__
await await_many_dispatch([receive, self.channel_receive], self.dispatch)
File "/dev/channels_sk/channels-master/channels/utils.py", line 50, in await_many_dispatch
await dispatch(result)
File "/dev/channels_sk/channels-master/channels/consumer.py", line 67, in dispatch
await handler(message)
File "/dev/channels_sk/channels-master/channels/generic/websocket.py", line 173, in websocket_connect
await self.connect()
File "/dev/channels_sk/tables/consumers.py", line 19, in connect
room.save()
File "/dev/channels_sk/.env/lib/python3.6/site-packages/django/db/models/base.py", line 729, in save
force_update=force_update, update_fields=update_fields)
File "/dev/channels_sk/.env/lib/python3.6/site-packages/django/db/models/base.py", line 769, in save_base
update_fields=update_fields, raw=raw, using=using,
File "/dev/channels_sk/.env/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 178, in send
for receiver in self._live_receivers(sender)
File "/dev/channels_sk/.env/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 178, in <listcomp>
for receiver in self._live_receivers(sender)
File "/dev/channels_sk/tables/signals.py", line 20, in room_save_handler
'update': instance.population,
File "/dev/channels_sk/.env/lib/python3.6/site-packages/asgiref/sync.py", line 34, 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.

消费者.py
from channels.generic.websocket import AsyncWebsocketConsumer
import json
import time
from .models import Room
from django.db.models import F

class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name

# create room or increment
room, created = Room.objects.get_or_create(title=self.room_name)
pop = room.population + 1
room.population = F('population') + 1
room.save()

# Join room group
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)

await self.accept()

# send new population to group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'pop_message',
'population': pop,
}
)

async def disconnect(self, close_code):
room = Room.objects.get(title=self.room_name)
pop = room.population - 1
if room.population == 1:
if room.permanent == False:
room.delete()
else:
room.population = F('population') - 1
room.save()

# send new population to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'pop_message',
'population': pop,
}
)

# Leave room group
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)

# Receive message from WebSocket
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']


# Send message to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message,
)

# Receive message from room group
async def chat_message(self, event):
message = event['message']

# Send message to WebSocket
await self.send(text_data=json.dumps({
# 'type': 'chat_message',
'message': message,
}))

# change in room group population
async def pop_message(self, event):
content = event['type']
population = event['population']

# Send message to WebSocket
await self.send(text_data=json.dumps({
# 'type': 'pop_message',
'content': content,
'population': population,

}))


class RoomConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.group_name = 'chat_room_dash'
print("joined dash room")

# Join room group
await self.channel_layer.group_add(
self.group_name,
self.channel_name
)

await self.accept()

async def disconnect(self, close_code):
print("left dash room")
pass

async def send_message(self, text_data=None):
print(text_data)
labels = []
data = []
for room in Room.objects.all()[:3]:
labels.append(room.title)
data.append(room.population)

await self.send(text_data=json.dumps(
{
'labels': labels,
'data': data,

}))

信号.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync



from .models import Room


@receiver(post_save, sender=Room)
def room_save_handler(sender, instance, **kwargs):
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
'chat_room_dash',
{
'type': 'send_message',
'update': instance.population,
}
)

到目前为止

在阅读错误时,我尝试了建议的解决方案,方法是将 signals.py room_save_handler() 更改为异步并等待消息发送到群组。

然而,当我手动更新模型或当用户进入聊天室时,这并没有发送消息。

我的客人是,当第一个消费者调用 room.save() 时,room_save_handler() 也被调用,这意味着异步调用中有一个异步调用。

任何帮助都会很棒!

最佳答案

我有同样的问题,我已经在下面解决了 way :

import asyncio

from django.db.models.signals import post_save
from django.dispatch import receiver
from channels.layers import get_channel_layer


from .models import Room


@receiver(post_save, sender=Room)
def room_save_handler(sender, instance, **kwargs):
channel_layer = get_channel_layer()
loop = asyncio.get_event_loop()

coroutine = async_to_sync(channel_layer.group_send)(
'chat_room_dash',
{
'type': 'send_message',
'update': instance.population,
}
)
loop.run_until_complete(coroutine)

关于python - 信号和 django channel 聊天室,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50299749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com