celery异步实现发送邮件验证激活账号

1 篇文章 0 订阅
1 篇文章 0 订阅

参考的源码:

参考的源码:
实现邮件发送
用户账号通过邮件激活

配置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测试

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
首先需要安装celery和redis: ``` pip install celery redis ``` 接下来创建一个celery实例: ```python from celery import Celery app = Celery('tasks', broker='redis://localhost:6379/0') ``` 这里的`tasks`是celery任务的名称,`broker`是指定消息代理的地址,这里使用的是redis。 然后定义一个发送邮件的任务: ```python import smtplib from email.mime.text import MIMEText from email.utils import formataddr @app.task def send_email(to_email, subject, content): from_email = 'xxx@example.com' # 发件人邮箱 password = 'password' # 发件人邮箱密码 msg = MIMEText(content, 'plain', 'utf-8') msg['From'] = formataddr(('Sender', from_email)) msg['To'] = formataddr(('Recipient', to_email)) msg['Subject'] = subject try: server = smtplib.SMTP('smtp.example.com', 587) # 发件人邮箱SMTP服务器地址和端口号 server.starttls() server.login(from_email, password) server.sendmail(from_email, [to_email], msg.as_string()) server.quit() print(f'Successfully sent email to {to_email}') except Exception as e: print(f'Error: {e}') ``` 这里使用了`smtplib`库来发送邮件,需要设置发件人邮箱、密码、SMTP服务器地址和端口号,以及收件人邮箱、邮件主题和内容。 最后,在主程序中调用这个任务: ```python from tasks import send_email result = send_email.delay('recipient@example.com', 'Test email', 'Hello, world!') ``` 这里使用了`delay()`方法来异步执行任务,将收件人邮箱、邮件主题和内容作为参数传递给任务。任务执行完毕后,可以通过`result.get()`方法获取任务的返回值。 完整代码如下: ```python from celery import Celery import smtplib from email.mime.text import MIMEText from email.utils import formataddr app = Celery('tasks', broker='redis://localhost:6379/0') @app.task def send_email(to_email, subject, content): from_email = 'xxx@example.com' # 发件人邮箱 password = 'password' # 发件人邮箱密码 msg = MIMEText(content, 'plain', 'utf-8') msg['From'] = formataddr(('Sender', from_email)) msg['To'] = formataddr(('Recipient', to_email)) msg['Subject'] = subject try: server = smtplib.SMTP('smtp.example.com', 587) # 发件人邮箱SMTP服务器地址和端口号 server.starttls() server.login(from_email, password) server.sendmail(from_email, [to_email], msg.as_string()) server.quit() print(f'Successfully sent email to {to_email}') except Exception as e: print(f'Error: {e}') if __name__ == '__main__': result = send_email.delay('recipient@example.com', 'Test email', 'Hello, world!') print(result.get()) ``` 注意要在`if __name__ == '__main__':`中调用任务,否则会导致循环引用的问题。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值