【发布时间】:2019-04-02 10:45:40
【问题描述】:
我正在努力解决使用 Django Channels 制作通知系统的问题。它在本地运行良好。在生产中(在 Webfaction 上),它可以正常工作几分钟,然后停止工作并出现以下错误消息:
ERROR - server - Exception inside application:
File "/home/client/.virtualenvs/project/lib/python3.6/site-packages/channels/sessions.py", line 175, in __call__
return await self.inner(receive, self.send)
File "/home/client/.virtualenvs/project/lib/python3.6/site-packages/channels/middleware.py", line 41, in coroutine_call
await inner_instance(receive, send)
File "/home/client/.virtualenvs/project/lib/python3.6/site-packages/channels/consumer.py", line 54, in __call__
await await_many_dispatch([receive, self.channel_receive], self.dispatch)
File "/home/client/.virtualenvs/project/lib/python3.6/site-packages/channels/utils.py", line 57, in await_many_dispatch
await task
File "/home/client/.virtualenvs/project/lib/python3.6/site-packages/channels_redis/core.py", line 400, in receive
assert not self.receive_lock.locked()
我正在使用:
- aioredis==1.1.0
- asgiref=2.3.2
- 频道==2.1.3
- channels-redis==2.3.0
- django==2.1.2
- Redis 4.0.11
- Python 3.6.6
这都是使用django的开发服务器。
我的消费者看起来像这样:
class NotificationConsumer (AsyncJsonWebsocketConsumer):
slight_ordering = True
async def connect (self):
self.user = self.scope["user"]
await self.accept()
group_name = "notifications_{}".format(self.user.employee.pk)
await self.channel_layer.group_add(group_name, self.channel_name)
async def disconnect (self, code):
self.user = self.scope["user"]
group_name = "notifications_{}".format(self.user.employee.pk)
await self.channel_layer.group_discard (group_name, self.channel_name)
async def user_notification (self, event):
await self.send_json(event)
通知在创建时发送,使用 post_save 信号:
@receiver(post_save, sender=Notification)
def new_notification (sender, instance, **kwargs):
channel_layer = get_channel_layer()
group_name = "notifications_{}".format(instance.employee.pk)
async_to_sync(channel_layer.group_send)(
group_name, {
"type": "user.notification",
"event": "New notification",
"notification_pk": instance.pk,
}
)
我的路由如下所示:
application = ProtocolTypeRouter({
'websocket': AuthMiddlewareStack(
URLRouter(
[url(r'^notifications/$', NotificationConsumer),]
)
),
})
最后,我在前端使用 WebSocketBridge:
const webSocketBridge = new channels.WebSocketBridge();
webSocketBridge.connect('/notifications/');
webSocketBridge.listen(function(action, stream){
//show the notification
});
如果有人知道可能发生的事情以及为什么我会收到此 self.receive_lock.locked() 错误,我将不胜感激。
谢谢
【问题讨论】:
标签: python django websocket redis django-channels