我正在尝试使用flask-mail在芹菜任务中发送邮件,但是我继续收到此运行时错误RuntimeError('working outside of application context',)
。这是我在文件中的代码:
from app import app
from celery import Celery
from flask.ext.mail import Message
from flask import current_app
# config
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'
# set up celery
celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)
# put the processing task here
@celery.task
def send_results(filename, email_addr):
msg = Message('testing email', recipients=[email_addr])
msg.body = 'testing this funct'
with app.app_context():
current_app.mail.send(msg)
print(filename)
print(email_addr)
请注意,其中有app.app_context()
行(此时我不确定它是否正确)
另一件需要注意的事情是应用程序还没有完全完成"然而。具体来说,我的意思是应用程序的创建由一个名为create_app的函数处理,如下所示:https://github.com/swarajd/seq2flux/blob/master/app/startup/create_app.py
此功能在manage.py中调用:https://github.com/swarajd/seq2flux/blob/master/manage.py
我尝试在名为views.py
的文件中调用此任务,该文件处理所有视图。处理此问题的一个功能如下:
@core_blueprint.route('data_analysis', methods=['GET', 'POST'])
@login_required
def data_analysis():
# print(request.form)
form = DataAnalysisForm(CombinedMultiDict((request.files, request.form)))
# print(form)
if (request.method == 'POST' and form.validate()):
# print(request.form)
# print(request.files)
file = request.files['seqFile']
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
mail_engine = current_app.extensions.get('mail', None)
# print(mail_engine)
# print(current_user)
send_results.delay(filename, current_user.email)
flash('processing job scheduled!')
# Redirect to home page
return redirect(url_for('core.data_analysis'))
return render_template('core/data_analysis.html', form=form)
重要的一行是:send_results.delay()
我的问题是:即使使用上下文,为什么会抛出运行时错误?
答案 0 :(得分:0)
发生这种情况的原因是因为电子邮件MESSAGE本身是在with
语句之外创建的,导致运行时错误。