Flashを使ってログイン時のエラーメッセージを表示する
コード
python.py
from flask import Flask, flash
# Login
@app.route('/login')
def login():
return render_template('login.html')
# lockin check
@app.route('/logincheck', methods=['POST'])
def logincheck():
user_id = request.form['user_id']
pwd = request.form['password']
session['username'] = user_id
# make pwd hashed by "get_digest()"" function
password = get_digest(pwd)
id_pwd_hash = get_user_data()
if user_id in id_pwd_hash:
if password == id_pwd_hash[user_id]:
session['login'] = True
else:
flash('Authentication failed! Please check your input.')
session['login'] = False
else:
flash('Authentication failed! Please check your input.')
session['login'] = False
if session['login']:
return redirect(url_for('index'))
else:
return redirect(url_for('login'))
login.html
{% block main %}
<h2>Login Authentication</h2>
<h3>Please input User ID and Password!</h3>
{% with messages = get_flashed_messages() %}
{% for message in messages %}
<li>
<i>
<font color="orange">{{ message }}</font>
</i>
</li>
{% endfor %}
{% endwith %}
<form method="POST" action="/logincheck">
<p><input placeholder="User ID" type="text" name="user_id"></p>
<p><input placeholder="Password" type="password" name="password"></p>
<p><input type="submit" value="SEND"></p>
</form>
{% endblock %}
ポイント
- flash()モジュールをインポートする
- pythonファイルにflashメッセージを記載
- {% with messages = get_flashed_messages() %} メッセージ {% endwith %} htmlのフォームの上部に記載