Best way to notify browser on database updates?
我使用django已有近6个月了,它对我所使用的几乎所有类型的网站都适用。
但是,最近,我在创建网站时偶然发现了一个问题,该用户在该网站上收到有关其他用户更新的任何博客帖子的通知。
我的方法是这样的:
在我的模板中,我一直像这样进行ajax调用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | $(document).ready(function() { setInterval(function(){get_updates();}, 10000); function get_updates(){ $.ajax({ type:"GET", datatype: 'json', url:"{% url 'models.views.update_notification' %}", success: function(data) { if(data.updated){ $.("content").load('notifications.html'); } } }) }) }); } class UpdateNotificationView(View): def get(self, request): user = FriendUser.objects.get(name='friend') msg = {"updated" : user.is_updated()} return HttpResponse(simplejson.dumps(msg)) |
假设
1 | {{ notification }} |
这里的问题是,我认为每隔x秒/分钟不断进行这样的ajax调用不是一个好主意。
有没有一种方法可以在数据库直接更新到浏览器后立即从后端推送更新,而无需轮询这样的更新?
还是django不能弥补?
我想您应该看看django-comet或其他类似彗星的项目。
它将允许您将响应从服务器推送到用户的浏览器。
彗星上的Wiki页面:http://en.wikipedia.org/wiki/Comet_(编程)
此外,让我分享一个指向该主题的出色答案的链接:https://stackoverflow.com/a/4403209/2795926