如何使用Python(Django)进行SSE? [英] How can I make SSE with Python (Django)?
问题描述
我有两个不同的页面,一个(A)显示从模型对象获取的数据,另一个(B)更改其字段。
我希望将帖子数据从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:
template
<!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\n\n' % datetime.datetime.now()
return StreamingHttpResponse(event_stream(), content_type='text/event-stream')
urls
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\n\n' % text
return StreamingHttpResponse(event_stream(), content_type='text/event-stream')
和 send_notification
函数在<$ c中创建一个条目$ c>通知模型(只需在代码中的任意位置调用此函数)即可:
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
)
就是这样,很简单。
这篇关于如何使用Python(Django)进行SSE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!