Django - 如何在 celery 和 redis 中使用异步任务队列

Django - How to use asynchronous task queue with celery and redis

#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 在访问时加载一段时间。我如何 运行 my_func 在后台使用 celery 和 redis 以便 index.html 加载得更快?

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

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

调用它

如前所述,您可能不需要芹菜。这是从案例 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/ 时发生的事情是我 立即 看到:

大约 10 秒后,我看到:

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