我有一个Flask应用程序,我希望使用Flask-Babel
发送电子邮件,该模板在模板中有可翻译的字符串。
@celery.task
def send_email(user_email=None):
with app.app_context():
html = render_template('user/email_template.html')
subject = lazy_gettext(u'Subject Line')
send_email(user_email, subject, html)
@app.route('/index/', methods=['GET', 'POST'])
@login_required
def index():
...
send_email.delay(
user_email=user.email,
)
email_template.html
<p>{{ _('Email Test') }}</p>
这会导致错误:
AttributeError: 'NoneType' object has no attribute 'ugettext'
当我在没有Celery的情况下调用send_email
函数时,这不会发生。我是否必须以某种方式将应用程序上下文传递给Celery?
N.B。为清晰起见缩写
修改
完整的堆栈跟踪:
[2016-03-28 12:08:30,528: ERROR/MainProcess] Task main.send_unlock_email[98f520d4-fadf-4272-8c14-17d6c16bf182] raised unexpected: AttributeError("'NoneType' object has no attribute 'ugettext'",)
Traceback (most recent call last):
File "<path>.envs/<env>/local/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
R = retval = fun(*args, **kwargs)
File "<path>.envs/<env>/local/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__
return self.run(*args, **kwargs)
File "<path>flask-projects/<env>/<env>/views/main.py", line 84, in send_unlock_email
html = render_template('user/successfull_unlock.html')
File "<path>.envs/<env>/local/lib/python2.7/site-packages/flask/templating.py", line 128, in render_template
context, ctx.app)
File "<path>.envs/<env>/local/lib/python2.7/site-packages/flask/templating.py", line 110, in _render
rv = template.render(context)
File "<path>.envs/<env>/local/lib/python2.7/site-packages/jinja2/environment.py", line 989, in render
return self.environment.handle_exception(exc_info, True)
File "<path>.envs/<env>/local/lib/python2.7/site-packages/jinja2/environment.py", line 754, in handle_exception
reraise(exc_type, exc_value, tb)
File "<path>flask-projects/<env>/<env>/templates/user/successfull_unlock.html", line 1, in top-level template code
<p>{{ _('Email Test') }}</p>
File "<path>.envs/<env>/local/lib/python2.7/site-packages/jinja2/ext.py", line 132, in _gettext_alias
return __context.call(__context.resolve('gettext'), *args, **kwargs)
File "<path>.envs/<env>/local/lib/python2.7/site-packages/jinja2/ext.py", line 138, in gettext
rv = __context.call(func, __string)
File "<path>.envs/<env>/local/lib/python2.7/site-packages/flask_babel/__init__.py", line 116, in <lambda>
lambda x: get_translations().ugettext(x),
AttributeError: 'NoneType' object has no attribute 'ugettext'