Django async update a single page template

后端 未结 2 819
死守一世寂寞
死守一世寂寞 2021-01-07 03:22

I have a django view with this function to get the data for a template:

def get_context_data(self, **kwargs):
  context = super(MyView, self).get_context_dat         


        
2条回答
  •  遥遥无期
    2021-01-07 03:46

    If you plan in going ahead with celery, you will need 2 views:

    1.viewA that loads the main page (without the extra_data - maybe a spinning gif animation in it's place in the HTML, to convey to the user that there is still data to be loaded in the page). This view will also start the celery task (but will not wait for it to complete). It would look similar to:

    def viewA(request):
        task = a_long_running_function.delay()
    
        return render_to_response('viewA.html', {'task_id': task.id})
    

    2.viewB that will be accessed via AJAX after the user's browser loads viewA (it's purpose will be to provide the extra_data which was not loaded by viewA). It would look similar to:

    def viewB(request, task_id):
        extra_data = a_long_running_function.AsyncResult(task_id) 
    
        if extra_data.ready():
           return render_to_response('viewB.html', {'extra_data': extra_data.get()})
    
        return HttpResponse('')
    

    Once the user's browser finishes loading viewA, you will need a bit of javascript to start running AJAX requests every X seconds/minutes to viewB to attempt to retrieve the celery task result (based on the celery task id that is available). Once the AJAX request successfully retrieves the task result from viewB, it can make it visible to the user.

提交回复
热议问题