Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

question from:https://stackoverflow.com/questions/65946843/django-rest-framework-action-when-request-comes-in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
126 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...