将Django服务器发送的事件与数据库帖子保存一起使用 [英] Using Django Server Sent Events with Database post save

查看:50
本文介绍了将Django服务器发送的事件与数据库帖子保存一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Django Framework中实现服务器发送事件(SSE).对我来说很明显,我可以像这样实现view:

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

但是,只要在数据库表中从表的post_save中创建一个新条目,我都想触发SSE调用,因为eventStream是生成器函数,在这里我怎么能实现这一点.

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.

推荐答案

Django是围绕请求/响应周期构建的,这意味着它不适用于websocket甚至SSE.在您的示例中,除非在视图中使用预订队列(rabbitmq,redis pubsub)并在信号处理程序中发送数据,否则无法将post_save信号传播到视图.

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:

  • 长时间轮询
  • Django频道
  • 像nodejs或龙卷风这样的异步解决方案,或者与Django并存

这篇关于将Django服务器发送的事件与数据库帖子保存一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆