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)defdebug_task(self):print('Request: {0!r}'.format(self.request))
tasks.py 文件
from linkcheck import celery_app
from django.core.mail import EmailMultiAlternatives
@celery_app.task
defadd_two_num(x, y):return x + y
__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',)
views.py
from.tasks import*
result = add_two_num.delay(1,2)
使用函数名.delay()即可使函数异步执行
可以通过result.ready()来判断任务是否完成处理
如果任务抛出一个异常,使用result.get(timeout=1)可以重新抛出异常
如果任务抛出一个异常,使用result.traceback可以获取原始的回溯信息