如何使用Python(Django)生成SSE?

2024-06-16 14:47:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个不同的页面,一个(A)显示从模型对象获取的数据,另一个(B)更改其字段。 我希望当post数据从B发送到服务器时,服务器更改A中的值。 最好的办法是什么?在

这个例子可能对我有用,但它是用PHP编写的。。。有没有办法用Python复制它? https://www.w3schools.com/html/html5_serversentevents.asp


Tags: 数据对象https模型服务器comhtmlwww
2条回答

这是来自Django的w3schools的工作示例:

模板

<!DOCTYPE html>
<html>
<body>

<h1>Getting server updates</h1>
<div id="result"></div>

<script>
if(typeof(EventSource) !== "undefined") {
  var source = new EventSource("stream/");
  source.onmessage = function(event) {
    document.getElementById("result").innerHTML += event.data + "<br>";
  };
} else {
  document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>

</body>
</html>

视图

^{pr2}$

网址

urlpatterns = [
    path('stream/', views.stream, name='stream')
]

更新:

如果要管理通知,可以创建如下模型:

from django.db import models

class Notification(models.Model):
    text = models.CharField(max_length=200)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    sent = models.BooleanField(default=False)

然后创建查找第一个未发送通知的视图并发送它:

@login_required
def stream(request):
    notification = Notification.objects.filter(
        sent=False, user=request.user
    ).first()

    text = ''

    if notification:
        text = notification.text
        notification.sent = True
        notification.save()

    return HttpResponse(
        'data: %s\n\n' % text,
        content_type='text/event-stream'
    )

以及在Notification模型中创建一个条目的send_notification函数(只需从代码中的任何位置调用此函数):

def send_notification(user, text):
    Notification.objects.create(
        user=user, text=text
    )

就这样,就这么简单。在

读了this后,我想我理解了整个事情(如果我错了请评论)

Django本机不支持keep-alive连接。
这意味着,当客户端从服务器获取消息时,连接将在之后立即关闭(就像任何经典的HTTP请求/响应周期一样)。在


与text/event-stream请求不同的是,客户机每秒自动尝试重新连接到服务器(长度可以通过retry参数更改)

不幸的是,在这种情况下使用SSE似乎没有任何兴趣,因为它有与轮询相同的缺点(即每X秒发生一个请求/响应周期)。在



正如其他答案中提到的,我需要django通道来创建一个持久连接,以防止HTTP请求/响应开销,并确保消息立即发送

相关问题 更多 >