Django使用celery进行异步任务

  • 安装celery pip install celery
  • 在项目文件夹下添加文件celery.py用于初始化一个celery的app对象,
  • 在需要使用异步任务的app下创建 tasks.py 文件用于定义异步任务,注意tasks.py必须建在各app的根目录下,且只能叫tasks.py,不能随意命名
  • 在项目的 __init__.py 文件下导入celery_app,
  • 在项目需要异步运行的地方调用异步函数
    在这里插入图片描述
  1. celery.py 文件
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings

# set the default Django settings module for the 'celery' program.
project_name = os.path.split(os.path.abspath('.'))[-1]
project_settings = '%s.settings' % 'linkcheck'
# 设置环境变量
os.environ.setdefault('DJANGO_SETTINGS_MODULE', project_settings)
# 实例化Celery
app = Celery(project_name)
app.conf.update(
    broker_url='amqp://guest:guest@localhost:5672//', # 消息队列,可以更换为官方支持的broker
    task_serializer='json',
    accept_content=['application/json'], 
    result_serializer='json',
    timezone='Asia/Shanghai',
    enable_utc=True,
)
# Using a string here means the worker will not have to
# pickle the object when using Windows.
# 使用django的settings文件配置celery
app.config_from_object('django.conf:settings')

# Celery加载所有注册的应用
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)


@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))
  1. tasks.py 文件
from linkcheck import celery_app
from django.core.mail import EmailMultiAlternatives

@celery_app.task
def add_two_num(x, y):
    return x + y

  1. __init__.py
from __future__ import absolute_import, unicode_literals

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ('celery_app',)
  1. views.py
from .tasks import *

result = add_two_num.delay(1,2)

使用函数名.delay()即可使函数异步执行
可以通过result.ready()来判断任务是否完成处理
如果任务抛出一个异常,使用result.get(timeout=1)可以重新抛出异常
如果任务抛出一个异常,使用result.traceback可以获取原始的回溯信息
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值