1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Flask】flashを使ったメッセージの表示

Posted at

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のフォームの上部に記載

auth_failure.png

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?