Using Django Sent Server Events with Database Retention

I am trying to implement Server Sent Events (SSE) in the Django Framework. It is clear to me that I can implement view as follows:

 @csrf_exempt def event_stream(request): def eventStream(): yield "data:Server Sent Data\n\n" response = HttpResponse(eventStream(), content_type="text/event-stream") response['Cache-Control'] = 'no-cache' return response 

But I want to call an SSE call whenever a new record is created in the database table, from the post_save table. How could I achieve this here, since eventStream here is a generator function.

+7
source share
2 answers

Django builds around a request / response loop, which means it doesnโ€™t work with websites or even with SSE. In your example, there is no way to extend the post_save signal to the view if you are not using a subscription to the queue (rabbitmq, redis pubsub) in the view and send data in the signal handler.

Consider other push server solutions:

  • Long survey
  • Django channels
  • An asynchronous solution like nodejs or a tornado instead of or next to Django
+9
source

Read about signals. https://docs.djangoproject.com/en/dev/topics/signals/ In this case, you should use the request_started and post_save signals

0
source

Source: https://habr.com/ru/post/1262542/


All Articles