定期获取数据并使用Django显示 [英] Periodically fetch data and display it with Django
问题描述
我想在我的Django应用程序中实现一种实时"通知系统.
I would like to implement a kind of "real-time" notification system in my Django application.
我会将一些发给特定用户的消息存储在数据库中. 当用户登录到应用程序中时,如果数据库中有针对他的通知,则该应用程序将使用消息框架显示该通知. 当他单击该消息时,该消息将从数据库中删除.
I would store some messages destined to a specific user in my database. When a user is logged in the application, if there is a notification for him in the database, then the application displays it using the messages framework. When he clicks on the message, it is deleted from the database.
我有点卡在每分钟获取数据"的东西上.我听说过芹菜( http://docs.celeryproject.org/en/latest/#),但我想确定这是潜水之前去那里的方法,因为它的设置和使用似乎有些复杂.
I am a bit stuck on the "fetch the data every minute" thing. I heard of celery (http://docs.celeryproject.org/en/latest/#), but I would like to be sure it is the way to go there before diving in, because it seems a bit complicated to set up and use.
如果有一种简便的方法来守护Django功能,或者已经存在与我想要做的类似的事情,我将不胜感激!
If there is an easy way to daemonise a django fonction, or if something similar to what I want to do already exist, I would appreciate any hint !
推荐答案
如果只是简单的任务,则可以使用Ajax.
If is just a simple task, you may do with Ajax.
只需为ajax查询声明一个URL:
Just declare one URL for the ajax query:
#urls.py
...
url(r'^ajax/my_query$', my_app.views.ajax_processor)
...
然后在您的my_app/views.py
中:
#views.py
def ajax_processor(request):
... do the processing you want as if it is a normal web request.
... like querying the database
... you can return a `json` dictionary
... or a normal `render_to_response` template with html
那应该在服务器端完成.在客户端,将jQuery与$.ajax
函数一起使用并执行以下操作将很可爱:
That should do on the server side. On the client side it would be lovely to use jQuery with the $.ajax
function and do this:
$.ajax({
url:'/ajax/my_query', // a normal get request
success:function(data){ // success is the callback when the server responds
/* if is json what you decided to return then process the json dict
if is normal html render it wherver you want
*/
}
});
这只是一个简单的设置,在服务器端有一些代码,在客户端有一些代码.
Is just a simple set up, a bit of code in server-side and a bit of code in client-side.
如果您打算开发一个高度实时的应用程序,那么您应该依赖一个更好的库,但是如果您只需要进行少量异步查询,那么您可以考虑采用这种方式.
If you are planning to develop a heavily real-time based application then you should rely on a better library, but if you only need to do a little query asynchronous then you may consider this way.
这是W3Schools提供的一个很好且简单的Ajax教程,可帮助您了解Ajax,和此处,您可以找到有关使用ajax/jquery进行轮询的有用信息.
Here is a good and simple ajax tutorial provided by the W3Schools to help you understand Ajax, and here you can find useful information about polling with ajax/jquery.
祝你好运!
这篇关于定期获取数据并使用Django显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!