簡體   English   中英

向Celery注冊多個任務

[英]Register multiple tasks with Celery

我正在構建一個簡單的幫助程序類,用於在Django和Celery中發送電子郵件。

我的密碼

import logging

from celery import Task
from django.conf import settings
from django.core.mail import send_mail
from render_block import render_block_to_string

from optilimo.celery import app
from reservations.models import Reservation

logger = logging.getLogger(__name__)


class Mailer(Task):
    """
    Build emails from template and send them via Celery.
    Includes some helper functions as well.
    """
    template = None
    from_email = settings.DEFAULT_FROM_EMAIL
    name = 'mailer'
    max_retries = 3

    def build_context(self, ctx):
        return ctx

    def run(self, to_email, ctx, *args, **kwargs):
        ctx = self.build_context(ctx)

        subject = render_block_to_string(self.template, 'subject', ctx)
        plain = render_block_to_string(self.template, 'plain', ctx)
        html = render_block_to_string(self.template, 'html', ctx)

        send_mail(subject, plain, self.from_email,
                  [to_email], html_message=html)
        logger.info('Email sent to {}'.format(to_email))

    def on_success(self, retval, task_id, args, kwargs):
        super(Mailer, self).on_success(retval, task_id, args, kwargs)
        logger.info('Email with task ID {} was successfuly sent.'.format(task_id))

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        super(Mailer, self).on_failure(exc, task_id, args, kwargs, einfo)
        logger.error('Email with task ID {} was failed to send.'.format(task_id))
        logger.error('Error: {}'.format(str(exc)))


class QuoteRequestMailer(Mailer):
    template = 'mails/internal/quote_request.html'


class ReservationDetailsMailer(Mailer):
    template = 'mails/internal/reservation_details.html'

    def build_context(self, ctx):
        reservation = Reservation.objects.first()
        return {'reservation': reservation}


app.tasks.register(QuoteRequestMailer)
app.tasks.register(ReservationDetailsMailer)

問題

當我注冊多個任務時(例如,在上面的代碼中),無論我調用什么類,都將調用最后注冊的get任務。

例如,如果我這樣做:

mail = QuoteRequestMailer()
mail.delay(to_email='demo@mail.com', ctx={'data':'Test'})

工作人員將執行ReservationDetailsMailer任務,而不是QuoteRequestMailer任務。 如何以這種方式注冊多個任務?

我可以通過將name屬性添加到子類來解決它。

class QuoteRequestMailer(Mailer):
    name='mailer.quote_request'  # Important
    template = 'mails/internal/quote_request.html'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM