Django+Celery+Redis实现异步任务(发送邮件)
安装如下依赖库
pip install Celery pip install django-celery pip install django-redis
还要安装本地的Redis服务
settings.py 文件中添加如下代码(需要163邮箱开通SMTP服务)
import djcelery djcelery.setup_loader() BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.163.com' EMAIL_PORT = 25 EMAIL_HOST_USER = 'your mail@163.com' EMAIL_HOST_PASSWORD = 'your password' EMAIL_FROM = '<your mail@163.com>'
EMAIL_TO = 'send to@xxx.com'
INSTALLED_APPS = (
...
'djcelery'
)
与settings.py同级目录下的__init__.py添加如下代码
import celery from .celery import app as celery_app
在settings.py同级目录下创建celery.py,并添加如下代码
from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings') app = Celery('myshop') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
在你的app目录下创建tasks.py,并添加你需要执行的任务(在这里是发送邮件)
# coding: utf-8 from celery import task from django.core.mail import send_mail from .models import Order from myshop import settings @task() def send_email(): """ Task to send an e-mail notification when an order is successfully created. """ title = 'Django发送邮件' message = ('本邮件为程序所发,请忽视').decode('utf-8') mail_sent = send_mail(title, message, settings.EMAIL_FROM, [settings.EMAIL_TO]) return mail_sent
在你的view.py中调用,执行该任务
from .tasks import order_createddef order(request):
..... # launch asynchronous task send_email.delay(order.id)
.....