django celery异步任务创建
时间: 2025-02-01 12:32:42 浏览: 21
配置Celery
为了使Django项目能够利用Celery执行异步任务,需先完成必要的环境搭建工作。这包括安装所需的软件包以及设置相应的配置项。
安装依赖库
通过pip工具来安装celery
及其消息代理(如Redis),命令如下:
pip install celery redis
设置Django项目的Celery实例
创建一个新的Python文件用于初始化Celery应用,在此假设命名为celery.py
并放置于与manage.py
同级目录下[^2]。
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project_name.settings')
app = Celery('your_project_name')
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
app.config_from_object('django.conf:settings', namespace='CELERY')
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
在此基础上还需修改__init__.py
以确保当Django启动时自动加载Celery应用程序:
# 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',)
更新Settings Configuration
编辑settings.py
加入Celery的相关参数定义,例如指定使用的Broker URL和Result Backend等选项[^1]。
CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
# Optional configurations, see http://celery.readthedocs.org/en/latest/configuration.html
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'UTC'
以上步骤完成后便可以在任意Django App内开发具体的异步任务函数了。
编写异步任务
在期望添加异步操作的应用程序中新建tasks模块,并编写具体业务逻辑的任务方法。下面给出一个简单的例子展示如何发送邮件作为后台作业处理:
from celery import shared_task
from django.core.mail import send_mail
@shared_task
def send_email(subject, message, recipient_list):
"""Send an email asynchronously."""
try:
result = send_mail(
subject=subject,
message=message,
from_email=None, # Use DEFAULT_FROM_EMAIL setting
recipient_list=recipient_list,
fail_silently=False,
)
return f'Successfully sent {result} emails.'
except Exception as e:
raise ValueError(f"Failed to send mail due to error: {str(e)}")
此时调用该任务的方式有两种:一种是在视图或其他地方直接触发;另一种则是借助调度器定期运行特定任务。
相关推荐


















