调用异步任务时,芹菜引发异常:"NameError: global name * is not defined"



执行异步任务时,芹菜引发异常

#case where error is thrown
send_registration_email.delay("test", "test@gmail.com", {})

当我执行省略芹菜

的代码时,不会出现此错误。
#case where code is executed correctly
send_registration_email("test", "test@gmail.com", {})

我如何执行我的异步任务与芹菜,所以我将和摆脱这个错误?

错误
[2015-10-12 14:50:57,176: ERROR/MainProcess] Task tasks.core.email.send_registration_email[5f96bee3-9df7-42ce-b726-c7086e82b954] raised unexpected: NameError("global name 'Mailer' is not defined",)
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__
    return self.run(*args, **kwargs)
  File "/srv/www/compare/htdocs/tasks/core/email.py", line 6, in send_registration_email
    @shared_task
NameError: global name 'Mailer' is not defined

芹菜任务
# email.py 
from __future__ import absolute_import
from celery import shared_task
from utilities.helpers.mailer import Mailer
@shared_task
def send_registration_email(email_type="", recipient="", data={}):
    Mailer.send_email(email_type, recipient, data)
<<h3>梅勒类/h3>
# mailer.py
from __future__ import absolute_import
from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template

class Mailer():
    @staticmethod
    def send_email(email_type="", recipient="", data={}):
        try:
            email = Mailer.create_email(email_type, recipient, data)
            email.send()
            return True
        except Exception as e:
            return False
    @classmethod
    def create_email(self, email_type, recipient, data):
        subject = ""
        message = ""
        sender_email = "mailgun@xxx.mailgun.org"
        if email_type == "test":
            subject = "Test subject"
            content_html = "<html><body><h1>Test</h1></body></html>"
        email = EmailMultiAlternatives(subject, None, sender_email, [recipient])
        email.attach_alternative(content_html, "text/html")
        return email

你需要重新启动你的worker,以便在你的worker实例中看到对文件的更改。芹菜不监视文件更改,所以如果您在工作程序运行时更改了任何文件,则需要重新启动工作程序。

对于开发目的,这可以通过使用自动重新加载特性来避免:

当启用自动加载时,工作线程启动一个额外的线程来监视文件系统中的更改。新模块被导入,已经导入的模块在检测到变化时被重新加载,如果使用了预分叉池,子进程将完成它们正在做的工作并退出,这样它们就可以被有效地重新加载代码的新进程所取代。

这是一个实验性的特性,应该只在开发环境中使用

正如@grrrrrr建议的那样,重新启动celery worker修复了这个问题。在我的例子中,芹菜工人是由主管运行的,所以我不得不重新启动主管。

相关内容

  • 没有找到相关文章

最新更新