如何使用Celery(不带第三方软件包)发送Django的密码重置电子邮件?

时间:2019-01-15 15:32:01

标签: python django django-forms rabbitmq celery

首先,我知道这个问题已经在here那里得到了回答,该问题使用了第三方软件包django-celery-email,但我试图弄清楚如何做到这一点而又不依赖任何第三方党库。

所以我需要使用 Celery 异步发送密码重置电子邮件。

我的forms.py文件如下:

from django import forms
from accounts.tasks import send_mail
from django.contrib.auth.forms import PasswordResetForm as PasswordResetFormCore


class PasswordResetForm(PasswordResetFormCore):
    email = forms.EmailField(max_length=254, widget=forms.TextInput(
        attrs={
            'class': 'form-control',
            'id': 'email',
            'placeholder': 'Email'
        }
    ))

    def send_mail(self, subject_template_name, email_template_name,
                  context, from_email, to_email, html_email_template_name=None):
        """
        This method is inherating Django's core `send_mail` method from `PasswordResetForm` class
        """
        super().send_mail(subject_template_name, email_template_name,
                  context, from_email, to_email, html_email_template_name)

我正在尝试通过 Celery send_mail类的PasswordResetForm方法发送邮件。我的意思是用 Celery 呼叫super().send_mail(...)。我在 Celery send_mail文件中也有一个tasks.py函数,我试图在其中传递super().send_mail方法作为参数从那里调用它。

现在我的tasks.py文件看起来像这样:

from __future__ import absolute_import, unicode_literals


@shared_task
def send_mail():
    pass

我将RabbitMQCelery一起用作消息代理

1 个答案:

答案 0 :(得分:0)

好的,我遇到了一个可行的解决方案。这是我的解决方法。

我已经按照以下步骤更改了forms.py

from django import forms
from accounts.tasks import send_mail
from django.contrib.auth.forms import PasswordResetForm as PasswordResetFormCore


class PasswordResetForm(PasswordResetFormCore):
    email = forms.EmailField(max_length=254, widget=forms.TextInput(
        attrs={
            'class': 'form-control',
            'id': 'email',
            'placeholder': 'Email'
        }
    ))

    def send_mail(self, subject_template_name, email_template_name, context, 
                  from_email, to_email, html_email_template_name=None):
        context['user'] = context['user'].id

        send_mail.delay(subject_template_name=subject_template_name, 
                        email_template_name=email_template_name,
                        context=context, from_email=from_email, to_email=to_email,
                        html_email_template_name=html_email_template_name)

更改后的tasks.py就像下面的

from __future__ import absolute_import, unicode_literals
from accounts.models import User
from django.contrib.auth.forms import PasswordResetForm


@shared_task
def send_mail(subject_template_name, email_template_name, context,
              from_email, to_email, html_email_template_name):
    context['user'] = User.objects.get(pk=context['user'])

    PasswordResetForm.send_mail(
        None,
        subject_template_name,
        email_template_name,
        context,
        from_email,
        to_email,
        html_email_template_name
    )