from rest_framework.generics import CreateAPIView from rest_framework.response import Response from rest_framework.exceptions import ParseError from apps.auth1.serializers import EmailCodeSerializer from django.core.cache import cache from apps.utils.tools import rannum from server.settings import get_sysconfig class EmailCodeView(CreateAPIView): """发送邮箱验证码 发送邮箱验证码用于注册 """ authentication_classes = [] permission_classes = [] serializer_class = EmailCodeSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) vdata = serializer.validated_data email = vdata.get('email') cache_key = f'email_code_{email}' # 生成6位验证码 code = rannum(6) print(code) # 缓存验证码,有效期5分钟 cache.set(cache_key, code, 60 * 5) # 使用 MyThread 发送验证码邮件 from django.core.mail import send_mail from apps.utils.thread import MyThread def send_email(): config = get_sysconfig() base_name_short = config['base']['base_name_short'] send_mail( subject=f'{base_name_short}-验证码', message=f'您的验证码是:{code},5分钟内有效。如非本人操作,请忽略此邮件。', from_email=None, # 使用默认发件人 recipient_list=[email], fail_silently=False ) thread = MyThread(target=send_email) thread.start_p() return Response({'ok_msg': '验证码已发送'})