Django框架下用户注册邮箱验证功能的实现

  • 来源:新网
  • 更新日期:2018-03-13

摘要:Django框架下用户注册邮箱验证功能的实现 需要熟悉Django的MVT模型 需要用到celery + Redis settings.py文件下的操作:配置celery和redis:import djcelery djcelery.setup_loader() BROKER_URL = \'redis://127.0.0.1:6379/2\'然后在INSTALLED_APPS中注册celery:INS

Django框架下用户注册邮箱验证功能的实现

t011eb70c3c21c16c91.jpg

需要熟悉Django的MVT模型
需要用到celery + Redis

settings.py文件下的操作:

配置celery和redis:

import djcelery djcelery.setup_loader() BROKER_URL = \'redis://127.0.0.1:6379/2\'

然后在INSTALLED_APPS中注册celery:

INSTALLED_APPS = ( \'django.contrib.admin\', \'django.contrib.auth\', \'django.contrib.contenttypes\', \'django.contrib.sessions\', \'django.contrib.messages\', \'django.contrib.staticfiles\', \'djcelery\', # 注册djcelery )

配置服务端邮箱:

# 发送邮件配置 EMAIL_BACKEND = \'django.core.mail.backends.smtp.EmailBackend\' # smtp服务器地址 EMAIL_HOST = \'your email server address\' # smtp服务器端口号 EMAIL_PORT = 25 # 发送邮件的邮箱 EMAIL_HOST_USER = \'your email address\' # 在邮箱中设置的客户端授权密码 EMAIL_HOST_PASSWORD = \'your email password\' # 你的邮箱密码 # 收件人看到的发件人 EMAIL_FROM = \'projectname<your email address>\' task.py文件下的操作:

在对应app下新建并编写celery的task.py文件:

# 定义celery任务 from celery import task from django.core.mail import send_mail from django.conf import settings @task def send_register_success_mail(username, password, email): \'\'\' 用户注册成功之后发送邮件任务 \'\'\' msg = \'<h1>欢迎您成为****会员</h1>请您记好您的注册信息:<br/>用户名:\' + username + \'<br/>密码:\' + password send_mail(\'欢迎信息\', \'\', settings.EMAIL_FROM, [email, ], html_message=msg) views.py文件下的操作:

在views.py文件下导入send_register_success_mail方法:

from user.tasks import send_register_success_mail # 导入发送邮件任务方法 @require_POST def send_mail(self,username, password, email): \'\'\'以非阻塞的方式发送邮件\'\'\' send_register_success_mail.delay(username=username, password=password,email=email) redirect(\'/\') # 返回到网页根目录

发送邮件只需要调用send_mail方法即可。