In the flask:flashing documentation, I encounter the following situation.
JavaScript
x
20
20
1
from flask import Flask, flash, redirect, render_template, request, url_for
2
3
app = Flask(__name__)
4
app.secret_key = b'_5#y2L"F4Q8znxec]/'
5
6
@app.route('/')
7
def index():
8
return render_template('index.html')
9
10
@app.route('/login', methods=['GET', 'POST'])
11
def login():
12
error = None
13
if request.method == 'POST':
14
if request.form['username'] != 'admin' or request.form['password'] != 'secret':
15
error = 'Invalid credentials'
16
else:
17
flash('You were successfully logged in')
18
return redirect(url_for('index'))
19
return render_template('login.html', error=error)
20
And here is the Jinja2 used HTML file.
JavaScript
1
13
13
1
<!doctype html>
2
<title>My Application</title>
3
{% with messages = get_flashed_messages() %}
4
{% if messages %}
5
<ul class=flashes>
6
{% for message in messages %}
7
<li>{{ message }}</li>
8
{% endfor %}
9
</ul>
10
{% endif %}
11
{% endwith %}
12
{% block body %}{% endblock %}
13
So I wonder that even if there is no function passed in to the HTML file by using return statement in Python file, Jinja2 can read get_flashed_messages()
function, which is a function under the flask module. How is this possible?
Advertisement
Answer
Messages to be flashed get appended to session
, a global object that jinja2 has access to along with what you return in your route functions
.
From the flask github repo flask/src/flask/helpers.py:
JavaScript
1
9
1
from .globals import session
2
3
def flash(message: str, category: str = "message") -> None:
4
5
flashes = session.get("_flashes", [])
6
flashes.append((category, message))
7
session["_flashes"] = flashes
8
9
flask‘s source code is available on github and it is well worth the exploration.