Polling a Celery Task with Ajax
I have a Celery task that populates a PostgreSQL database over the course of a few minutes. I want to retrieve the current data from the database in a Django view and send it to a template where it will be constantly re-displayed according to the progress of the task. So, I want to update the template in real-time.
Currently, I have a view that calls the Celery task and gets the result of the task. It then renders the template and sends it the result of the task in the form of a string, as well as the id of the task.
I am not very familiar with AJAX, but from what I've read I will need another view that AJAX will call to retrieve the most up-to-date result of the task.
Here is the code so far:
View that renders the template:
def dashboard(request):
result = prepare_database.delay()
result_str = result.get()
return render(request, 'appname/template.html',
{'task_id': result.task_id(), 'str': result_str})
View that gets the current data
def current_data(request):
task_id = request.GET.get('task_id')
if task_id:
async_result = AsyncResult(task_id)
return JsonResponse({'data': async_result.get()})
Ajax to poll the task (again, very new to AJAX):
$.ajax({
url: '/current_data/',
method: 'GET',
data: {
data: 'data'
},
success: function(response) {
// Update the HTML with the results
}
});
Please let me know if my entire approach is flawed, as I am not too sure this is the right way to go. Also let me know if there is anything else I should clarify or elaborate on.