1.环境版本:
Django 3.2.12
celery 5.3.4
eventlet 0.33.3
flower 2.0.1
redis 3.5.3
项目名称:new_project
2.celery配置(settings.py)
# celery # django-celery 配置的部分 # Broker配置,使用Redis作为消息中间件 BROKER_URL = 'redis://127.0.0.1:6379/0' # BACKEND配置,这里使用redis CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0' # 结果序列化方案 CELERY_RESULT_SERIALIZER = 'json' # 任务结果过期时间,秒 CELERY_TASK_RESULT_EXPIRES = 60 * 60 * 24 # 时区配置 CELERY_TIMEZONE = 'Asia/Shanghai' # # 指定导入的任务模块,可以指定多个 # CELERY_IMPORTS = ( # 'new_project.tasks', # )
3.celery.py配置(settings.py同目录)
import os import django from celery import Celery from django.conf import settings # 设置系统环境变量,安装django,必须设置,否则在启动celery时会报错 # djangoProject1.settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'new_project.settings') django.setup() celery_app = Celery('new_project') celery_app.config_from_object('django.conf:settings') celery_app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) 所有官方配置参考:http://docs.celeryproject.org/en/latest/userguide/configuration.html
4.__init__.py(settings.py同目录)
from .celery import celery_app __all__ = ['celery_app']
5.任务配置(需要异步执行的方法,task.py与settings.py同目录)
说明:示例程序,转换pdf文件为doc,方法必须加上@shared_task装饰器
import random from pdf2docx import Converter from celery import shared_task @shared_task def change_file(file_path): docx_name = file_path[:-4] + str(random.randint(100000, 999999)) + '.doc' print("file_path: ", file_path) print("docx_name: ", docx_name) # 加载pdf文档 cv = Converter(file_path) cv.convert(docx_name) cv.close() print("file success!") return 1024
6.启动Django项目
7.启动celery命令:celery -A new_project worker -l debug -P eventlet
8.启动flower命令:celery -A new_project flower,执行后会出现Visit me at http://0.0.0.0:5555,将ip替换为127.0.0.1即可访问
9.任务调用(一般为views.py)
说明:比如页面提交了一份文件,需要后台慢慢去处理的情况,下面在一个方法里面展示了调用任务和查询结果,用sleep模拟等待时间
调用时需要加上.delay方法进行异步处理,使用AsyncResult.get()获取结果,state和get()结果分别是SUCCESS 和1024
def file(request): file = "E:\\new_project\static\\tc.pdf" res = change_file.delay(file) print("res", res) num = 0 while num < 30: num += 1 ar = result.AsyncResult(str(res)) # print("ar", ar) if ar.ready(): print(ar.state, ar.get()) else: print(ar.state) sleep(2) return render(request, 'file.html')
标签:flower,settings,eventlet,redis,new,celery,file,import,py From: https://www.cnblogs.com/lytcreate/p/17784095.html