首页 > 其他 > 详细

初始celery

时间:2020-05-13 15:23:56      阅读:44      评论:0      收藏:0      [点我收藏+]

使用celery执行异步任务

  1. 下载celery,redis

pip3 install 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

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

初始celery

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!