初始celery

使用celery执行异步任务

  1. 下载celery,redis

pip3 install celery
#在这里我使用的是celery==4.2.2
#当celery版本过低的话celery配置可能会略有不同
#启动redis服务端
  • 在django项目的配置文件中配置返回值格式以及中间件IP

# Celery settings
​
CELERY_BROKER_URL = 'redis://localhost'#: Only add pickle to this list if your broker is secured
#: from unwanted access (see userguide/security.html)
CELERY_ACCEPT_CONTENT = ['json']
CELERY_RESULT_BACKEND = 'redis://localhost'
CELERY_TASK_SERIALIZER = 'json'
  • 在django项目的项目文件夹下创建一个celery.py文件并写入如下代码

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
​
# 设置“celery”程序的默认Django设置模块。
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'demo.settings')
​
app = Celery('demo')
# 这里的demo表示你项目的名字
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')
​
# 从所有已注册的Django app configs加载任务模块
app.autodiscover_tasks()
  • 在我们app的views.py中写入如下代码

from django.shortcuts import render,HttpResponse
from .tasks import add
# Create your views here.
def index(request):
    add.delay(1,2)
    return HttpResponse('200 OK')
  • 在app中创建一个tasks.py文件用来放置任务

import time
from celery import Celery
​
celery_app = Celery('tasks', backend='redis://localhost', broker='redis://localhost')
# this is celery settings
# this is a function about need many time
@celery_app.task
def add(a, b):
    time.sleep(5)
    return a + b

然后我们就可以启动项目,并且启动celery的worker进程,并访问index路由

查看worker窗口是否正常执行

worker出现上图字样,没有ERROR字眼,就表示我们的celery已经准备就绪了,然后就可以进行访问查看worker是否正常处理异步操作

这样就表示我们的celery的异步执行任务就可以正常工作了

celery在win10上的坑

  • celery在win10上运行可能会出现`Celery ValueError: not enough values to unpack (expected 3, got 0)`这个报错`

  解决办法

  先安装一个eventlet

pip install eventlet

  在启动worker的时候加入一个参数

celery -A <mymodule> worker -l info -P eventlet

  然后就可以正常执行任务了

原文地址:https://www.cnblogs.com/wang-xing-hao/p/12882218.html