Django如何自定义rest-auth重置密码以使用SendGrid发送电子邮件

时间:2019-02-24 06:51:17

标签: django django-rest-framework

我正在使用Django rest-auth,并且正在编写一种向用户发送电子邮件以重置密码的方法。但是,我不想使用默认的发送电子邮件的方式,而是要使用SendGrid来发送电子邮件。

views.py

class PasswordResetSerializer(serializers.Serializer):
    email = serializers.EmailField()
    password_reset_form_class = PasswordResetForm

    def get_email_options(self):
        return {}

    def validate_email(self, value):
        self.reset_form = self.password_reset_form_class(data=self.initial_data)
        if not self.reset_form.is_valid():
            raise serializers.ValidationError(self.reset_form.errors)
        return value

    def save(self):
        request = self.context.get('request')
        opts = {
            'use_https': request.is_secure(),
            'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
            'request': request,
        }

        opts.update(self.get_email_options())
        self.reset_form.save(**opts)

serializers.py

class PasswordResetView(GenericAPIView):
    serializer_class = PasswordResetSerializer
    permission_classes = (AllowAny,)

    def post(self, request, *args, **kwargs):

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(
            {"detail": _("Password reset e-mail has been sent.")},
            status=status.HTTP_200_OK
        )

SendGrid函数

class SendEmail(View):
def get(self, request, *args, **kwargs):
    from_email_address = self.request.GET['from_email_address']
    to_email_address = self.request.GET['to_email_address']
    email_subject = self.request.GET['email_subject']
    email_content = self.request.GET['email_content']

    sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY)
    from_email = Email(from_email_address)
    to_email = Email(to_email_address)
    subject = email_subject
    content = Content("text/plain", email_content)
    mail = Mail(from_email, subject, to_email, content)
    response = sg.client.mail.send.post(request_body=mail.get())
    print(response.status_code)
    return HttpResponse('Email has been sent!')

我知道我必须先使用

url(r'^password/reset/$', PasswordResetView.as_view(), name='rest_password_reset'),

向用户发送包含链接的电子邮件,其中包含“ uid”和“ token”以重置密码。然后使用:

url(r'^password/reset/confirm/$', PasswordResetConfirmView.as_view(), name='rest_password_reset_confirm'),

重设密码。

我在这里遇到的问题是我不确定在PasswordResetSerializer中如何生成“令牌”和“ uid”并将其发送给用户。因此,我不确定如何更改序列化程序和视图,以便可以使用SendGrid函数发送eamil。

有人可以告诉我该怎么做吗?预先感谢!

0 个答案:

没有答案