Search code examples
pythondjangodjango-rest-frameworkdjango-channels

Django Rest Framework action when request comes in


I'm creating a Django project that uses Django REST Framework for the API. Other projects will be making POST, PUT, and DELETE requests to this project. When one of those requests comes in, I want to send a message to a websocket group using channels. For some reason I am struggling to do this.

I am using ThreadViewSet, which extends ModelViewSet, for a model named Thread.

class ThreadViewSet(ModelViewSet):
    queryset = Thread.objects.all()
    serializer_class = ThreadSerializer

I have tried adding the channels call to this class but it doesn't seem to be run:

class ThreadViewSet(ModelViewSet):
    queryset = Thread.objects.all()
    serializer_class = ThreadSerializer
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)("group", {'type': 'new_message', 'message': "New Thread"})

The next thing I tried was overriding create(), update(), and destroy() and this worked, but it seemed like so much work for one simple task. Am I missing something? There has to be an easier way to do this.


Solution

  • You can just override the dispatch method if the message should be send everytime a request comes in:

    class ThreadViewSet(ModelViewSet):
        queryset = Thread.objects.all()
        serializer_class = ThreadSerializer
        channel_layer = get_channel_layer()
    
        def dispatch(self, *args, **kwargs):
            async_to_sync(channel_layer.group_send)("group", {'type': 'new_message', 'message': "New Thread"})
            return super().dispatch(*args, **kwargs)
    

    Keep in mind that this one will always trigger an message voer websocket regardless the result of the query.