简体   繁体   中英

substitutes of time.sleep for while loop in django views

Below is what I want to do in django views.

import requests, time
def SOME_VIEW_FOR_AJAX(request):
    if request.is_ajax():
        response = requests.get('API_URL_START_TASK')
        # response is like {'ready':false, 'status':'PENDING'}
        while not response['ready']:
            response = requests.get('API_URL_CHECK_TASK')
            time.sleep(1)
        result = response.get()
        # SOME MORE WORKS ...

via api (celery is on the other PC), this view initiates a celery task, constantly checks a status of the task, and gets the result if the task is done.

Here I concern the presence of time.sleep . This SO POST tells that the use of time.sleep is not appropriate because it holds a current thread. Is there a possible replacement of time.sleep for using django views? or is it allowable to use time.sleep for such a usage?

I am using Django 1.8.6, Apache 2.4 with mod_wsgi, Windows Server 2012 R2. Thanks in advance.

This is the wrong approach. The whole point of Celery is to offload long-running tasks so that they don't delay the response.

Instead you should immediately return a holding response, then get your front end - maybe via Ajax - to periodically request a status, probably from another view.

After the answer and the comment, thankfully, I leave a record for some later use.

As Daniel's answer says, the use of celery is not to wait during some computing by a server. Therefore it is natural for the front end to throw and check a celery task.

And the exposure of url in the javascript is not an issue for security matter. According to This SO post and that , I can regard the api url as a url of a single webpage, which is publicly known and a number of requests do not burden the server.

In my case in which the two servers respectively for the main web service and the computing is separated, CORS headers should be configured. This SO post notes that when you call ajax for a domain different from the host, jQuery does not set the appropriate header so that request.is_ajax() does not work. crossDomain: false in ajax code will solve this problem.

I am still searching and figuring out the server side security... As keni said, This may help.

I guess that my question did not summarize my concerns very well, so I wanted to do it here. Any tip will be welcome.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM