Python 如何在Flask中使用app_上下文?
这是我的结构。我在实现大型应用程序时遇到问题Python 如何在Flask中使用app_上下文?,python,flask,Python,Flask,这是我的结构。我在实现大型应用程序时遇到问题 ├─flasky │ ├─app/ │ │ ├─templates/ │ │ ├─static/ │ │ ├─main/ │ │ │ ├─__init__.py │ │ │ ├─errors.py │ │ │ ├─forms.py │ │ │ └─views.py │ │ ├─__init__.py │ │ ├─email.py │ │ └─models.py │ ├─migrations/ │
├─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)
我不知道如何调用模块来实现app.app\u context()。我希望它可以直接使用
发送电子邮件
功能,成功获取位置的应用程序/模板
。我发现了问题所在。我需要在email.py
中定义一个flask应用程序:
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
中遇到了一个新问题,我正在寻找解决方案。我发现“”提到了我的问题
werkzeug.routing.BuildError
BuildError: ('index', {}, None)
因为views.py
的输入参数为url\u 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())
但它无法启用发送电子邮件的功能。我发现“”提到了我的问题。我需要降级到flask\u mail==0.9.0
,这就解决了问题