"with"语句在Flask(Jinja2)中如何工作? [英] How does the 'with' statement work in Flask (Jinja2)?

查看:64
本文介绍了"with"语句在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 raises SyntaxError
  • with get_flashed_messages() as messages: pass raises AttributeError: __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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆