celery异步发短信

在bookstore中settings

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend

'EMAIL_HOST = 'smtp.126.com'

EMAIL_PORT = 25

# 发送邮件的邮箱

EMAIL_HOST_USER = '[email protected]'

# 在邮箱中设置的客户端授权密码

EMAIL_HOST_PASSWORD = 'xxxxxxxx'

# 收件人看到的发件人

EMAIL_FROM = 'dailyfresh'


在bookstore下创建celery,py文件

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', 'bookstore.settings')

app = Celery('bookstore', broker='redis://127.0.0.1:6379/6')

# 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()

@app.task(bind=True)

def debug_task(self):

        print('Request: {0!r}'.format(self.request))


创建task.py文件


from __future__ import absolute_import, unicode_literals

from celery import shared_task

from django.conf import settings

from django.core.mail import send_mail

@shared_task

def send_active_email(token, username, email): 

 '''发送激活邮件''' 

 subject = '用户激活'  # 标题 

 message = ''

 sender = settings.EMAIL_FROM # 发件人

 receiver = [email] # 收件人列表

 html_message = 'http://127.0.0.1:8000/user/active/'%token

 send_mail(subject, message, sender, receiver, html_message=html_message)

在view中

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from itsdangerous import SignatureExpired

from users.tasks import send_active_email


# 生成激活的token

 itsdangerous serializer = Serializer(settings.SECRET_KEY, 3600)

 token = serializer.dumps({'confirm':passport.id}) # 返回bytes

# 给用户的邮箱发激活邮件 # send_mail('用户激活', '', settings.EMAIL_FROM, [email], html_message='http://127.0.0.1:8000/user/active/' % token) 

 send_active_email.delay(token, username, email)

你可能感兴趣的:(celery异步发短信)