Search code examples
pythonflaskjinja2

How does the 'with' statement work in Flask (Jinja2)?


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

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 %}

I'd like to know how {% with messages = get_flashed_messages() %} works in terms of syntax.

I failed to recreate it in pure Python:

  • with messages = get_flashed_messages(): pass raises SyntaxError
  • with get_flashed_messages() as messages: pass raises AttributeError: __exit__

(I've imported get_flashed_messages from flask in both cases).


Solution

  • The with statement in Flask is not the same as the with statement in Python.

    Within python the equivalent would be this:

    messages = get_flashed_messages()