gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 06:14:35 24 4
gpt4 key购买 nike

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

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

最佳答案

如前所述,您可能不需要 celery 。这是从案例 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 中就这样结束了。

关于python - Django - 如何在 celery 和 redis 中使用异步任务队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32126366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com