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

2024-10-01 15:41:56 发布

您现在位置:Python中文网/ 问答频道 /正文

#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>

为了简单起见,我删除了很多代码,但这是它的要点。尽管我已经为myfunc发布了代码,但它是一个非常耗时的函数,它会导致索引.html当被访问时加载一段时间。我该如何在后台使用芹菜和redis来运行我的函数索引.html加载速度更快?在

我已经阅读了celery文档,但在设置celery和redis时仍然遇到问题。谢谢您。在


Tags: innoneindexreturnrequestmydefhtml
2条回答

这里不需要芹菜。您可以使用AJAX请求在页面上加载这些值。您应该创建一个单独的视图来计算此值,并在索引.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')

我的索引.html包含:

^{pr2}$

还有我的网址.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)
]

当我拜访时会发生什么本地主机:8000/测试/是我立即看到:

Initial visit

大约10秒后,我看到:

Image after 10 seconds

其思想是立即返回页面,并在操作完成后使用jquery获取操作结果,并相应地更新页面。您可以添加更多的东西,如进度条/加载图像等。例如,您可以在后台对pi1和{}进行处理,完成后将其加载到HTML中。在

相关问题 更多 >

    热门问题