celery异步实现发送邮件验证
参考的源码:
参考的源码:
实现邮件发送
用户账号通过邮件激活
配置Django和Celery
目录结构如下:
建立celery.py
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', 'example.settings')
app = Celery('example')
# 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')
# 自动添加所有app中的task.py中的任务
app.autodiscover_tasks()
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
在example/example/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和路由urls.py
在example/send_email/views.py中,代码如下:
from django.http import HttpResponse
from .tasks import task_send_email
from .tasks import download
import json
from . import models
# Create your views here.
def index(request):
#task_send_email.delay()
download.delay()
# download()
return HttpResponse('Download Done')
def email(request):
if request.method == 'POST':
dic = json.loads(request.body.decode('utf-8'))
name = dic.get('name')
password = dic.get('password')
email = dic.get('email')
user_obj = models.active.objects.filter(name=name).first()
if user_obj:
return HttpResponse('用户已存在')
user_obj = models.active.objects.create(name=name, password=password, email=email)
# 调用celery的发送邮件任务,将其加入消息队列,并将用户id传入
# result = send_email1.delay(user_obj.id)
result = task_send_email.delay(user_obj.id)
return HttpResponse('Email Done')
def active_user(request):
uid = request.GET.get('id')
#print(uid)
models.active.objects.filter(id=uid).update(is_active=1)
return HttpResponse('success')
在example/send_email/urls.py中,代码如下:
from django.contrib import admin
from django.urls import path
from . import views
from django.conf.urls import url
urlpatterns = [
path('', views.index, name='index'),
path('email', views.email),
url(r'^active_user/', views.active_user)
]
在example/example/urls.py中,代码如下:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('send_email.urls')),
]
在example/example/settings.py中的INSTALLED_APPS加入send_email
配置celery和redis
在example/example/setting.py中加入
CELERY_BROKER_URL = 'redis://127.0.0.1:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
建立tasks.py
新建一个tasks.py,放入example/send_email/task.py中
这个文件中,就可以定义我们要执行的异步任务了,比如发邮件。
from celery import shared_task
from django.core.mail import send_mail
import threading
from . import models
@shared_task
def task_send_email(id):
#获取刚才创建的用户,查到email
user = models.active.objects.filter(pk=id).first()
email = user.email
t = threading.Thread(target=send_mail, args=(
"激活邮件,点击激活账号", # 邮件标题
'点击该邮件激活你的账号,否则无法登陆', # 给html_message参数传值后,该参数信息失效
'xxx@qq.com', # 用于发送邮件的邮箱地址
[email], # 接收邮件的邮件地址,可以写多个
),
# html_message中定义的字符串即HTML格式的信息,可以在一个html文件中写好复制出来放在该字符串中
kwargs={
'html_message': "<a href='http://127.0.0.1:8000/active_user/?id=%s'>点击激活gogogo</a>" % id}
)
t.start()
return 'Email sent'
在send_email/views.py中创建函数来执行celery任务
同上。
设置example/example/setting.py邮件相关参数
EMAIL_HOST = 'smtp.qq.com'
EMAIL_HOST_USER = 'xxxxxx@qq.com'
EMAIL_HOST_PASSWORD = '你的邮箱SMTP的码'
EMAIL_USE_SSL = True
EMAIL_USE_TLS = False
EMAIL_PORT = 465
依次启用Redis,Celery,Diango
启动Redis
redis-server.exe redis.windows.conf
如果已经启动,则关闭后再启动
redis-cli.exe
shutdown
exit
启动Celery
example是settings所在的主目录名。
celery -A example worker -l info
启动Django
使用Postman测试