API request to already opened django channels consumer

旧时模样 提交于 2019-12-22 01:19:49

问题


I've got a django channels consumer communicating with a client. I've got a view from an external API that wants something from the client. From this view I want then to tell that consumer to ask a request to the client through his socket.

I'm currently exploring django rest framework but I can't find a way for now to directly ask anything to that consumer. Well I've got an idea but it involves creating another socket and communicate through channels' channel. But I wish I could get rid of this overload.


回答1:


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



来源:https://stackoverflow.com/questions/54329826/api-request-to-already-opened-django-channels-consumer

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