Search code examples
pythondjangowebsocketdjango-rest-frameworkdjango-channels

API request to already opened django channels consumer


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.


Solution

  • 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