开发者

How can request handlers communicate in Django?

If you make a long-running http request to a Djan开发者_如何学编程go application, can you send a second request to communicate with it? Can you share data between requests?

Pylons has a concept of application globals. Top level variables in node.js are all application globals. How can I do this in Django?


This is generally considered a bad idea, so I'm going to show you how it would usually be done. Most of the time, long-running tasks should be forked to the background, and updates from that task get placed in a global store (such as your database, memcached, or similar). This keeps your front-end server from getting bogged down with too many requests.

Using memcached (or any of the django cache backends), your code might look something like:

def long_running_task(number):
    cache.set("long_running_task_progress", 0, 60*60) # Store for 1 hour.
    for x in range(0, number):
        huge_calculation(number)
        cache.set("long_running_task_progress", (x / number), 60*60)
    cache.delete("long_running_task_progress")

def check_long_task(request):
    percent = cache.get("long_running_task_progress")
    if percent is None:
        return HttpResponse("There is no task running!")
    else:
        return HttpResponse("The task is %.2f percent complete." % (percent * 100))

Simply load the latter on an AJAX timer, and plop it into the page as needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜