问题
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.
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.
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 !
回答1:
If is just a simple task, you may do with Ajax.
Just declare one URL for the ajax query:
#urls.py
...
url(r'^ajax/my_query$', my_app.views.ajax_processor)
...
then in your 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
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.
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.
Good luck!
回答2:
Here are some options to consider:
celery. Yes, it's not that trivial to set up, but it's very easy to configure and use from your python/django side via django-celery. Also take a look at celery periodic tasks.
rq (Redis Queue). Simple job queue that is easy to set up.
django-cronograph. Creating and running cron jobs easily from admin commands.
Also see:
- Examples of Django and Celery: Periodic Tasks
- Django - Set Up A Scheduled Job?
来源:https://stackoverflow.com/questions/16522578/periodically-fetch-data-and-display-it-with-django