如何在Flask中使用app_context?

时间:2015-07-03 02:43:37

标签: python flask

这是我的结构。我有关于实施烧瓶大型应用的问题。

email.py

我在def send_email(to, subject, template, **kwargs): msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject, sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to]) with the_app.app_context(): msg.body = render_template(template + '.txt', **kwargs) msg.html = render_template(template + '.html', **kwargs) thr = Thread(target=send_async_email, args=[app, msg]) thr.start() return thr def send_async_email(app, msg): with app.app_context(): mail.send(msg) 进行编码时遇到了一些问题。

send_email

我不知道如何调用模块来实现the_app.app_context()。我希望它能指导app/templates函数让@RequestMapping(value = "stream", method = RequestMethod.GET) public ResponseBodyEmitter handleStreaming() { ResponseBodyEmitter emitter = new ResponseBodyEmitter(timeout); emitters.add(emitter); emitter.onCompletion(new Runnable() { @Override public void run() { emitters.remove(emitter); } }); emitter.onTimeout(new Runnable() { @Override public void run() { emitters.remove(emitter); } }); return emitter; } 位置成功。

1 个答案:

答案 0 :(得分:0)

我发现了问题所在。我需要在email.py中定义一个烧瓶应用程序:

import os
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
the_app = Flask(__name__, template_folder=tmpl_dir)

我遇到了werkzeug.routing.BuildError的新问题,我正在寻找解决方案。我发现“Flask error: werkzeug.routing.BuildError”提到了我的问题。

werkzeug.routing.BuildError
BuildError: ('index', {}, None) 

由于views.py的拼写错误为url_for(),我应该输入'main.index'。没错。

@main.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        ...
        return redirect(url_for('main.index'))
    return render_template('index.html',
                           form=form, name=session.get('name'),
                           known=session.get('known', False),
                           current_time=datetime.utcnow())

但它无法启用发送电子邮件的功能。我发现“Python Flask Email KeyError KeyError: 'mail'”提到了我的问题。我需要降级到flask_mail==0.9.0,这解决了问题。