Django - 如何使用芹菜和redis的异步任务队列

时间:2015-08-20 19:06:03

标签: python django asynchronous redis celery

#In my views.py file
pi1 = None
pis1 = None
def my_func():
    #Essentially this function sets a random integer to pi1 and pis1
    global pi1, pis1
    pi1 = randint(0,9)
    pis1 = randint(0,9)
    return        

def index(request):

    my_func()

    context = {
        "pi1" : pi1,
        "pis1" : pis1,
    }

    return render(request, "index.html", context)

#In the index.html file
<h1>{{ pi1 }}</h1>
<h1>{{ pis1 }}</h1>

为了简单起见,我删除了很多代码,但这是它的要点。尽管我为my_func发布了代码,但这是一个耗时的函数,导致index.html在访问时加载一段时间。如何使用celery和redis在后台运行my_func,以便index.html加载更快?

我已经阅读了芹菜文档,但我仍然无法设置芹菜和redis。谢谢。

2 个答案:

答案 0 :(得分:0)

你这里不需要芹菜。您可以使用AJAX请求在页面上加载这些值。您应该创建一个单独的视图来计算这个值,并在加载index.html之后用javascript调用它。

答案 1 :(得分:0)

如前所述,您可能不需要芹菜。以下是从案例2派生的示例:https://zapier.com/blog/async-celery-example-why-and-how/。它完全适合我:

from time import sleep
import json
from django.http import HttpResponse
from django.shortcuts import render

def main_view(request):
    return render(request, 'index.html')

def ajax_view(request):
    sleep(10) #This is whatever work you need
    pi1 = "This is pi1" #I just made pi1/pis1 random values
    pis1 = "This is pis1"
    context = {
        "pi1" : pi1,
        "pis1" : pis1,
    }
    data = json.dumps(context)

    return HttpResponse(data, content_type='application/json')

我的index.html包含:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Main View</title>
    <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
    <script>
    $(document).ready(function(){
        $.ajax({
            url: "/test_ajax/",
        }).done(function( data) {
            $("#pi1").text(data.pi1);
            $("#pis1").text(data.pis1); 
        });
    });
</script>
  </head>
  <body>
      <h1 id = "pi1">Loading</h1>
      <h1 id = "pis1">Loading</h1>
  </body>
</html>

我的urls.py包含:

from django.conf.urls import include, url
from django.contrib import admin
from testDjango.test import main_view, ajax_view

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^test/', main_view),
    url(r'^test_ajax/', ajax_view)
]

当我访问localhost时会发生什么:8000 / test /是我 立即 请参阅:

Initial visit

大约10秒后,我看到了:

Image after 10 seconds

我们的想法是您立即返回页面并使用jquery在完成操作时获取操作结果并相应地更新页面。您可以添加更多内容,例如进度条/加载图像等。对于您的示例,您可以在后台对pi1pis进行处理,并在完成后将其加载到HTML中。