【问题标题】:How to fix django channels consumers stopping to handle messages send to groups如何修复 django 频道消费者停止处理发送到组的消息
【发布时间】:2019-06-24 03:27:06
【问题描述】:

使用group_send() 向群组发送消息一段时间后突然停止工作。消费者的处理方法不再被调用。

重启daphne 可以解决一段时间的问题。

详情

日志中的任何地方都没有显示错误,只是消息不再由消费者处理。

我正在使用以下库:

  • aioredis==1.2.0
  • asgiref==2.3.2
  • channels-redis==2.3.2
  • 频道==2.1.6
  • 达芙妮==2.2.4
  • django==2.1.5
  • redis==3.0.1

代码

# settings.py
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {"hosts": [("localhost", "6379")]},
    }
}
# views.py
class ReceiveEventView(APIView):
    def post(self, request, *args, **kwargs):
        # payload: {"type": "event_triggered", "group": "warning", "message": "Button pressed"}
        # or
        # payload: {"type": "event_triggered", "group": "danger", "message": "Red Button pressed"}
        payload = json.loads(request.POST.get("payload", "{}"))
        if (payload.get("type") == "event_triggered"):
            async_to_sync(channel_layer.group_send)(payload.get("group"), payload)
        return HttpResponse(status=204)
# consumers.py
class EventConsumer(WebsocketConsumer):
    def connect(self):
        if not self.scope["user"].is_authenticated:
            return
        self.accept()
        for group in get_subscriptions(self.scope["user"]):
            async_to_sync(self.channel_layer.group_add)(group, self.channel_name)

    def disconnect(self, close_code):
        if not self.scope["user"].is_authenticated:
            return
        for group in get_subscriptions(self.scope["user"]):
            async_to_sync(self.channel_layer.group_discard)(group, self.channel_name)

    def event_triggered(self, event):
        logger.debug("Consumer::event_triggered()")
        self.send(text_data=json.dumps(event))

预期和实际结果

有一段时间Consumer::event_triggered() 出现在日志中,但突然停止。通过 WebSocket 从浏览器接收消息仍然有效。只是从group_send() 到消费者的传输中断了。

【问题讨论】:

  • 您使用哪个版本的 Python? 3.5.2? this version and channels 的组合似乎存在一个已知错误
  • 我使用的是 Python 3.5.3
  • 我已经编译了 Python 3.6.8 并且会看看它。希望它在明天之前可以毫无问题地运行。感谢您提供有关 Python 版本的提示。
  • 太好了,我已将其作为答案发布,如果可行,请不要忘记接受答案

标签: django websocket django-channels daphne


【解决方案1】:

我在 Python3.8 中遇到了这个问题。所以我通过切换到 Python3.6 来修复它

Django channels - Client receives message sometimes and not other times till it doesn't recieve it at all

【讨论】:

  • 是的!我也是,我也试过 python3.9 但它有同样的问题。我修复了切换到 python3.6
【解决方案2】:

有一个known bug 导致在 Python 3.5 中运行的 Channels 应用程序在一段时间后断开连接。更新到 Python 3.6 以获得可能的修复

【讨论】:

  • 再次感谢您的帮助。这确实是 Python 3.5 的一个问题。使用 Python 3.6 运行我的应用程序未显示此问题。
猜你喜欢
  • 1970-01-01
  • 2017-07-31
  • 2020-07-16
  • 1970-01-01
  • 2013-08-01
  • 1970-01-01
  • 2017-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多