Using Django Server Sent Events with Database post save

我与影子孤独终老i 提交于 2019-12-05 23:37:19

问题


I am trying to implement Server Sent Events(SSE) in Django Framework. It is clear to me that I can implement a view like this:

@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 trigger the SSE call whenever a new entry is made in a database table, from the post_save of the table, How I might be able to achieve that here since eventStream here is a generator function.


回答1:


Django is build around the request/response cycle which means that it doesn't work well with websockets or even SSE. In your example there is no way to propagade the post_save signal to the view unless you use subscribe to a queue (rabbitmq, redis pubsub) in the view and send data in the signal handler.

Consider other solutions to push from the server:

  • Long polling
  • Django channels
  • An asynchronus solution like nodejs or tornado instead or alongside Django



回答2:


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



来源:https://stackoverflow.com/questions/41556439/using-django-server-sent-events-with-database-post-save

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