首页 > 解决方案 > 如何在特定时间向用户显示消息 Django

问题描述

我想知道如何在 Django 中的某个时间在屏幕顶部向用户显示一条简单的消息。我一直无法在网上找到有关此的任何信息,所以我想知道我将如何去做。

我需要对 DateTime 做些什么吗?我会将代码包含在什么视图/模型中?

谢谢你提供的所有帮助 :)

标签: pythondjangodjango-views

解决方案


我仍然没有足够的声誉发表评论:

所以当你“阅读”这个答案时告诉我,我会删除它。如果您愿意,可以将有趣的部分复制/粘贴到评论中。

我认为确切的用例对于给出正确答案非常重要。这完全取决于您对“特定时间”的确切含义。

  1. 通知时间是预先知道的(javascript 警报)
  2. 定期询问 Django 服务器可以确定何时发送消息(轮询长/轮询)
  3. Django 服务器需要执行一些后台任务,消息应该在这个任务结束时发送

If you know already upfront (at the time the user opens the page) when this notification should happen, then Kostas Charitidis is right. The page can just use javascript to program a timer and it will be the web browser who can at the given time make a request to Django to fetch an display the message.

To 'push' anything from a web server to a web browser at a given time one requires something like continous polling, long polling, web-sockets.

If the notification time is not known upfront, then a polling approach would for example use a piece of javascript, that periodically (every few seconds / minutes / depending on your use case) queries the Django server whether a message should be fetched.

Long polling is an approach where the web browser performs a get request to the server and the server stalls the answer until the message should be sent. (if the requests times out a new polling request will be initiated) However to use long polling (efficiently) you'd need some special plugins on the server side to make this efficient / resource friendly.

If your web site does not need to be accessed from behind some old corporate (or paranoid) firewalls, then you might consider using web sockets (but there are still some public services / big companies who do block web sockets)

django-channels ( https://pypi.org/project/channels/ ) can help you with web socket notifications and some background tasks

celery ( https://pypi.org/project/celery/ ) can help you with running periodic / defered / tasks, but does not contain the means to send the message to your browser. Celery is one of the most recommended solutions, but is (in my opinion) rather painful to set up.

Depending on the project something lighter (like for example django-background-tasks https://pypi.org/project/django-background-tasks/ ) might do the job

You might look at the django message frame work ( https://docs.djangoproject.com/en/2.2/ref/contrib/messages/) . But very probably it is not the right answer in your context.


推荐阅读