"with"语句在Flask(Jinja2)中如何工作? [英] How does the 'with' statement work in Flask (Jinja2)?
问题描述
在Python中,您可以像这样使用with
语句(源):
In Python you can use the with
statement like this (source):
class controlled_execution:
def __enter__(self):
# set things up
return thing
def __exit__(self, type, value, traceback):
# tear things down
with controlled_execution() as thing:
# some code
在Flask/Jinja2中,使用Flash消息的标准过程如下(源):
In Flask/Jinja2, the standard procedure for using flash messages is the following (source):
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<!-- do stuff with `message` -->
{% endfor %}
{% endif %}
{% endwith %}
我想知道{% with messages = get_flashed_messages() %}
在语法方面如何工作.
I'd like to know how {% with messages = get_flashed_messages() %}
works in terms of syntax.
我无法在纯Python中重新创建它:
I failed to recreate it in pure Python:
-
with messages = get_flashed_messages(): pass
引发SyntaxError
-
with get_flashed_messages() as messages: pass
引发AttributeError: __exit__
with messages = get_flashed_messages(): pass
raisesSyntaxError
with get_flashed_messages() as messages: pass
raisesAttributeError: __exit__
(两种情况下我都从flask
导入了get_flashed_messages
).
(I've imported get_flashed_messages
from flask
in both cases).
推荐答案
Flask中的with
语句与Python中的with
语句不同.
The with
statement in Flask is not the same as the with
statement in Python.
在python中,等效项是这样:
Within python the equivalent would be this:
messages = get_flashed_messages()
这篇关于"with"语句在Flask(Jinja2)中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!