小编har*_*sak的帖子

Python Django:在数据库 save() 上从服务器向客户端发送消息

我想在保存模型时通知客户。我首先在 post_save 上创建了一个 django 信号。

@receiver(post_save, sender=Scooter)
async def scooter_post_update(sender, instance, created, **kwargs):
    # Notify client here
Run Code Online (Sandbox Code Playgroud)

接下来,我从 django-channels 创建了 AsyncConsumer 类并提供了它的路由。

// routing.py
    application = ProtocolTypeRouter({
        # Empty for now (http->django views is added by default)
        'websocket': AllowedHostsOriginValidator(
            AuthMiddlewareStack(
                URLRouter(
                    [
                        path('scooters/', ScootersUpdateConsumer)
                    ]
               )
        )
    )
})

// consumers.py
    class ScootersUpdateConsumer(AsyncConsumer):
        async def websocket_connect(self, event):
            print("Connected!", event)
            await self.send({
                "type": "websocket.accept"
            })
        async def send_message(self):
            await self.send({
                "type": "websocket.send",
                'text': 'Oy, mate!'
            })
        async def websocket_receive(self, event):
            print("Receive!", …
Run Code Online (Sandbox Code Playgroud)

python django django-signals websocket django-channels

5
推荐指数
1
解决办法
1397
查看次数