[英]How to use app_context in Flask?
This is my structure.这是我的结构。 I have problem about implementing flask large application.
我在实现 Flask 大型应用程序时遇到问题。
├─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
...
I encountered some problem When I was coding in email.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)
I don't know how to call modules to implement the_app.app_context().我不知道如何调用模块来实现 the_app.app_context()。 I hope that it can direct
send_email
function to get app/templates
of location to be successful.我希望它可以直接使用
send_email
函数来获取位置的app/templates
成功。
I found what the problem was.我发现了问题所在。 I needed to define a flask app in
email.py
:我需要在
email.py
定义一个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)
I encountered a new problem with werkzeug.routing.BuildError
, and I am searching for a solution.我遇到了
werkzeug.routing.BuildError
的新问题,我正在寻找解决方案。 I found " Flask error: werkzeug.routing.BuildError " mentioned my problem.我发现“ Flask error: werkzeug.routing.BuildError ”提到了我的问题。
werkzeug.routing.BuildError
BuildError: ('index', {}, None)
Because views.py
had a typo arg of url_for()
, I should type 'main.index'
.因为
views.py
有一个url_for()
的错字参数,我应该输入'main.index'
。 It's right.这是正确的。
@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())
But it can't enable the feature of sending email.但它不能启用发送电子邮件的功能。 I found " Python Flask Email KeyError KeyError: 'mail' " mentioned my problem.
我发现“ Python Flask Email KeyError KeyError: 'mail' ”提到了我的问题。 I needed to downgrade to
flask_mail==0.9.0
, which solved the problems.我需要降级到
flask_mail==0.9.0
,这解决了问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.