如何使用 Python (Django) 制作 SSE? [英] How can I make SSE with Python (Django)?

查看:56
本文介绍了如何使用 Python (Django) 制作 SSE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two different pages, one (A) that displays data taken from a model object, and one (B) that changes its fields. I would like that when the post data is sent from B to the server, the server changes the values in A. What is the best way to do it?

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

This example could work for me but it's in PHP... there is a way to replicate it whit Python? https://www.w3schools.com/html/html5_serversentevents.asp

推荐答案

这是 Django 中 w3schools 的工作示例:

This is working example from w3schools in Django:

模板

<!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>

观看次数

import datetime
import time
from django.http import StreamingHttpResponse

def stream(request):
    def event_stream():
        while True:
            time.sleep(3)
            yield 'data: The server time is: %s

' % datetime.datetime.now()
    return StreamingHttpResponse(event_stream(), content_type='text/event-stream')

网址

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

更新:

如果您想管理您的通知,您可以创建如下模型:

If you want to manage your notifications you can create the model like:

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)

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

Then create the view that is looking for the first unsent notification and sends it:

@login_required
def stream(request):
    def event_stream():
        while True:
            time.sleep(3)
            notification = Notification.objects.filter(
                sent=False, user=request.user
            ).first()

            text = ''

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

            yield 'data: %s

' % text

    return StreamingHttpResponse(event_stream(), content_type='text/event-stream')

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

And the send_notification function that creates an entry in the Notification model (just call this function from anywhere in your code):

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

就是这样,就这么简单.

That's it, simple as that.

这篇关于如何使用 Python (Django) 制作 SSE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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