API request to already opened django channels consumer

て烟熏妆下的殇ゞ 提交于 2019-12-04 20:38:20
Ken4scholars

From your reponse in the comments, it seems you want to send a message to the client through the consumer from your DRF view. You can check out the answer to a similar question.

First, you need to have a method in your consumer that sends a message back to the client:

...
async def send_alert(self, event):

    # Send message to WebSocket
    await self.send(text_data={
        'type': 'alert',
        'details': 'An external API api.external.com needs some data from you'
    })
...

So now you can send a message to this method. Assuming the client is connected to channel1, you can do this in your view:

from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
...

channel_layer = get_channel_layer()
async_to_sync(channel_layer.send)("channel1", {
    "type": "send.alert"
})
...

async_to_sync usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!