我希望在我的模型保存后通知客户端。
我首先创建了一个 post_save 的 Django 信号。
现在我的问题是,如何从scooter_post_update()方法中调用send_message()函数。
@receiver(post_save, sender=Scooter)
async def scooter_post_update(sender, instance, created, **kwargs):
# Notify client here
接下来,我基于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!", event)
async def websocket_disconnect(self, event):
print("Disconnected!", event)
现在我的问题是,如何从scooter_post_update()方法中调用send_message()函数。