【问题标题】:How to use app_context in Flask?如何在 Flask 中使用 app_context?
【发布时间】:2015-07-03 02:43:36
【问题描述】:

这是我的结构。我在实现烧瓶大型应用程序时遇到问题。

├─flasky
│  ├─app/
│  │  ├─templates/
│  │  ├─static/
│  │  ├─main/
│  │  │  ├─__init__.py
│  │  │  ├─errors.py
│  │  │  ├─forms.py
│  │  │  └─views.py
│  │  ├─__init__.py
│  │  ├─email.py
│  │  └─models.py
│  ├─migrations/
│  ├─tests/
│  │  ├─__init__.py
│  │  └─test*.py
│  ├─venv/
│  ├─requirements.txt
│  ├─config.py
│  └─manage.py
...

我在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)

我不知道如何调用模块来实现 the_app.app_context()。我希望它可以直接send_email函数获取位置的app/templates才能成功。

【问题讨论】:

    标签: python flask


    【解决方案1】:

    我发现了问题所在。我需要在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,这解决了问题。

    【讨论】:

      猜你喜欢
      • 2014-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-15
      • 2021-09-29
      • 2021-08-10
      • 2014-05-06
      • 1970-01-01
      相关资源
      最近更新 更多