1

So I would like to know the best practice for accomplishing the following:

def execute_expensive_operation(obj):
    #create instance of a model storing the relevant info to load the JSON into the template
    #includea `task` field that stores the name of the asynchronous task (obj.pk) so that the JSON can be loaded if the name of the task is known

def test_view(request):
    list_of_objects = [...] #will actually be dynamically loaded from the request
    task_dict = {}
    for obj in list_of_objects:
        task_dict[obj.pk] = execute_expensive_operation(obj).delay(obj.pk) #this could take a while, put it on queue (using celery)
    context = {"tasks":task_dict}
    return render_to_response("template.html",context)

"template.html" is going to load the JSON relevant to each obj in a row in a table

As this is set up above, the task_dict will actually be filled with AsyncResult objects rather than JSON. What I want to do, is dynamically load any row once the Asynchronous task related to that row has completed.

note:

I apologize for the non-specific methods, this is not something that is meant to be for anything specific, but more so for a general case that I have to deal with in a variety of different places. If there is any missing information, please let me know so that I can include it.

Community
  • 1
  • 1
Ryan Saxe
  • 17,123
  • 23
  • 80
  • 128
  • I don't think you can use `AsyncResult` at frontend to update results. You can send an ajax request and fetch the results. – Chillar Anand Sep 08 '14 at 16:37
  • Right, So I could use Ajax to fetch based on the name of the AsyncResult, but the issue is when do I call Ajax? How do I know, from the template, when a task has finished and there is information to load? – Ryan Saxe Sep 08 '14 at 16:42
  • You can automatically send an ajax request at periodic intervals based on the time required to complete your jobs. – Chillar Anand Sep 08 '14 at 17:20
  • okay, that sounds like it could work. Thanks! – Ryan Saxe Sep 08 '14 at 17:33

1 Answers1

1

Here is the gist of the idea to get started.

views.py

def test_view(request):

    # Normal web request processing. 
    # Return `json` dictionary

template.html

//making periodic ajax request. 
(function worker() {
$.ajax({
url: 'paht/to/url', 
success: function(data) {
  $('.result').html(data);
},
complete: function() {
  // Schedule the next request when the current one's complete
  setTimeout(worker, 5000);
}
});
})();

Also check out a simple ajax tutorial, making periodic ajax requests

Community
  • 1
  • 1
Chillar Anand
  • 27,936
  • 9
  • 119
  • 136
  • Okay thank you, I wont be able to test this out for a while, so +1, if it turns out to work well I will accept this when I can – Ryan Saxe Sep 08 '14 at 20:34