Django+Celery异步发送邮件
程序员文章站
2022-05-02 07:54:06
1. 安装 2. 项目目录 3. settings配置 4. celery模块 python 在task文件中 from __future__ import absolute_import, unicode_literals import os from celery import Celery s ......
-
安装
pip install django==1.11.7 pip install celery
-
项目目录
axf ├── alipay_config │ ├── alipay_rsa_public_key.pem │ └── app_rsa_private_key.pem ├── app │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ ├── models.py │ ├── __pycache__ │ ├── tests.py │ ├── urls.py │ ├── views_contstant.py 封装发送邮件函数 │ └── views.py ├── axf │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── task.py celery异步任务 ├── manage.py ├── middleware ├── static
-
settings配置
#email email_backend = 'django.core.mail.backends.smtp.emailbackend' email_use_tls = false email_use_ssl = true email_host = 'smtp.163.com' email_port = 465 email_host_user = 'sajinde@163.com' email_host_password = '**********' default_from_email = 'sam <sajinde@163.com>'
-
celery模块
#在task文件中 from __future__ import absolute_import, unicode_literals import os from celery import celery # set the default django settings module for the 'celery' program. # axf.settings:项目下的settings文件 os.environ.setdefault('django_settings_module', 'axf.settings') broker = 'redis://127.0.0.1:6379/6' # 将要进行的任务 backend = 'redis://127.0.0.1:6379/7' # 返回的结果 app = celery('app', broker=broker, backend=backend) # app = celery('app') # 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') # load task modules from all registered django app configs. app.autodiscover_tasks() #自动搜索所有的任务 'debug开启' # @app.task(bind=true) # def debug_task(self): # print('request: {0!r}'.format(self.request))
-
app下的init文件
from __future__ import absolute_import, unicode_literals from task import app as celery_app __all__ = ['celery_app']
-
发送邮件
from celery import shared_task @shared_task #可多次重用,@shared_task装饰可以让你无需任何具体的应用程序实例创建任务 def send_register_mail(username, email, token): # 发送邮件 print('------------------------------------') sleep(10) print('------------------------------------') title = '激活' msg = ' ' data = { 'username': username, 'url': 'http://127.0.0.1:8000/app/active/?token=' + token } temp = loader.get_template('user/active.html') html = temp.render(data) receiver = [ email, ] send_mail(title, msg, from_email=settings.default_from_email, recipient_list=receiver, html_message=html) print('send mail')
-
发送邮件调用
send_register_mail.delay(username, email, token)
-
开启任务队列
celery -a task worker -l info 或者 celery -a task worker --loglevel=info
上一篇: Redis的基操