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'
)
这是来自Django的w3schools的工作示例:
模板
视图
^{pr2}$网址
更新:
如果要管理通知,可以创建如下模型:
然后创建查找第一个未发送通知的视图并发送它:
以及在
Notification
模型中创建一个条目的send_notification
函数(只需从代码中的任何位置调用此函数):就这样,就这么简单。在
读了this后,我想我理解了整个事情(如果我错了请评论)
Django本机不支持keep-alive连接。 这意味着,当客户端从服务器获取消息时,连接将在之后立即关闭(就像任何经典的HTTP请求/响应周期一样)。在
与
text/event-stream
请求不同的是,客户机每秒自动尝试重新连接到服务器(长度可以通过retry
参数更改)不幸的是,在这种情况下使用SSE似乎没有任何兴趣,因为它有与轮询相同的缺点(即每X秒发生一个请求/响应周期)。在
正如其他答案中提到的,我需要django通道来创建一个持久连接,以防止HTTP请求/响应开销,并确保消息立即发送
相关问题 更多 >
编程相关推荐