- 实现添加邮件接口
- 配置邮件发送服务器
# 配置邮件服务器 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # 导入邮件模块 EMAIL_HOST = 'smtp.yeah.net' # 发邮件主机 EMAIL_PORT = 25 # 发邮件端口 EMAIL_HOST_USER = 'dailyfreshzxc@yeah.net' # 授权的邮箱 EMAIL_HOST_PASSWORD = 'dailyfresh123' # 邮箱授权时获得的密码,非注册登录密码 EMAIL_FROM = 'md<dailyfreshzxc@yeah.net>' # 发件人抬头
- 向user模型中添加邮箱状态字段
class User(AbstractUser): """用户模型类""" """"""“ email_active = models.BooleanField(default=False, verbose_name='邮箱验证状态')
- 提供更改邮箱接口
class EmailView(UpdateAPIView): serializer_class = EmailSerializer parser_classes = IsAuthenticated def get_object(self): return self.request.user
- 添加序列化器
class EmailSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'email'] extra_kwargs = { 'email': { 'required': True } } def update(self, instance, validated_data): instance.email = validated_data['email'] instance.save() # 提前添加上异步发送任务的实现 verify_url = instance.generate_email_verify_url() send_verify_email.delay(instance.email, verify_url) return instance
- 在models中添加生成验证邮箱的url
from itsdangerous import TimedJSONWebSignatureSerializer as TJSSerializer from django.conf import settings from . import constants """ 同级目录下添加constants,py文件用于设置量 # 邮箱验证链接有效期,单位是秒 VERIFY_EMAIL_TOKEN_EXPIRES = 3600 * 24 """ # Create your models here. class User(AbstractUser): """用户模型类""" ”“”“”“” def generate_email_verify_url(self): serializer = TJSSerializer(settings.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES) date = { 'user_id' : self.id, 'email' : self.email } token = serializer.dumps(date).decode() verify_url = 'http://www.md.site:8080/success_verify_email.html?token=' + token return verify_url
- 添加路由
“”“ 在user/urls.py中添加 ”“” # 添加邮箱 url(r'^email/$', views.EmailView.as_view()),
- 配置邮件发送服务器
- 实现异步发送邮件
- 添加异步任务
- 在celery_tasks下添加email文件夹(python package)
- 在celery_tasks/email添加tasks.py 文件
from celery_tasks.main import app from django.core.mail import send_mail from django.conf import settings @app.task(name='send_verify_email') def send_verify_email(to_email, verify_url): """ :param to_email: :param verify_url: :return: """ subject = "md邮箱验证" html_message = '<p>尊敬的用户您好!</p>' \ '<p>感谢您使用md。</p>' \ '<p>您的邮箱为:%s 。请点击此链接激活您的邮箱:</p>' \ '<p><a href="%s">%s<a></p>' % (to_email, verify_url, verify_url) send_mail(subject, "", settings.EMAIL_FROM, [to_email], html_message=html_message) print(verify_url)
- 在celery_tasks/main.py注册异步任务
# 自动注册celery任务 app.autodiscover_tasks(['celery_tasks.sms', 'celery_tasks.email'])
- 将异步任务添加到保存邮箱之后(在之前序列化器以及提前添加)
- 添加异步任务
- 实现后台验证邮件接口
- 实现端口
from rest_framework import status class VerifyEmailView(APIView): def get(self, request): token = request.query_params.get('token') if not token: return Response({'message':'缺少token'}, status=status.HTTP_400_BAD_REQUEST) user = User.check_email_verify_token(token) if not user: return Response({'message': '无效token'}, status=status.HTTP_400_BAD_REQUEST) user.email_active = True user.save() return Response({'message': 'OK'})
- 在models中实现验证逻辑
from itsdangerous import BadData # Create your models here. class User(AbstractUser): """用户模型类""" """""" @staticmethod def check_email_verify_token(token): pass serializer = TJSSerializer(settings.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES) try: date = serializer.loads(token) except BadData: return None else: user_id = date.get('user_id') email = date.get('email') try: user = User.objects.get(id=user_id, email=email) except User.DoesNotExist: return None else: return user
- 添加路由
# 验证邮箱 url(r'^emails/verification/$', views.VerifyEmailView.as_view()),
- 实现端口
做一个Django项目(1.9、实现添加邮箱并异步发送验证邮件提供后台验证接口)
最新推荐文章于 2021-12-14 09:58:16 发布