LoginSignup
1
0

More than 1 year has passed since last update.

【Flask】ログイン認証の結果でHTML出力を変更

Last updated at Posted at 2022-09-13

ログイン認証に成功すると最上部にログインユーザ名とログアウトが表示されるようにする

認証画面

スクリーンショット 2022-09-13 16.29.08.png

認証後の画面

スクリーンショット 2022-09-13 16.17.43.png

  • 認証に成功すると、最上部のブロックの中に"ユーザ名"と"ログアウト"のリンクが表示されるようになる

環境

  • macOSX Monterey
  • Python 3.10.6

ファイル構成

APP 
  ├─ static
  |    └─ style.css
  ├─ templates
  |      ├─ index.html
  |      └─ login.html
  └─ app.py

APPファイル

app.py
# save this as app.py
from flask import Flask, render_template, session, request, redirect, url_for
import os


app = Flask(__name__)

app.secret_key = os.urandom(21)
id_pwd = {'mash': 'mash123', 'cannu': 'cannu123'}


# index page
@app.route('/')
def index():
    if session.get('login'):
        user_name = request.args.get('uname')
        return render_template('index.html', user_name=user_name)
    else:
        return redirect(url_for('login'))

# login
@app.route('/login')
def login():
    return render_template('login.html')


# locgin check
@app.route('/logincheck', methods=['POST'])
def logincheck():
    user_id = request.form['user_id']
    password = request.form['password']

    if user_id in id_pwd:
        if password == id_pwd[user_id]:
            session['login'] = True
        else:
            session['login'] = False
    else:
        session['login'] = False
    
    if session['login']:
        return redirect(url_for('index', uname=user_id))
    else:
        return redirect(url_for('login'))


# logout
@app.route('/logout')
def logout():
    session.pop('login', None)
    return redirect(url_for('index'))


if __name__ == '__main__':
    app.run(debug=True)

ポイント

# index page

  • user_name = request.args.get('uname') とすることで下記のクエストリングから値を取り込む

# login check

  • 認証後にurl_forでindexを返すときに、引数として uname=user_id を渡している。
  • 引数はクエストリングとして渡される、"127.0.0.1:5000/?uname=(user_id)"

INDEXファイル

index.html
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>Top Page</title>
        <link rel="stylesheet" href="static/style.css">
    </head>

    <body>
        {% if user_name %}
        <div class="header">
            <div class="header-username">
                {{ user_name }}
                <a href="{{ url_for('logout')}}">Logout</a>
            </div>
        </div>
        {% endif %}

        <div class="container">
            <h2>Flask Web App</h2>

            <a href="/logout">Logout</a>
        </div>
    </body>
</html>

ポイント
user_name引数の受けとりの結果次第で、headerブロックが表示・非表示の挙動が変化する

{% if user_name %}
xxxx
{% endif %}

CSSファイル

style.css
body {
    width: 600px;
    height: auto;
    margin-left: auto;
    margin-right: auto;
    font-family: system-ui, sans-serif;
}

.header {
    background-color: lightskyblue;
    color: black;
    height: 20px;
    padding: 10px, 5px;
}

.header-username {
    float: right;
    font-size: 10px;
    margin: 5px 10px;
}

.container {
    background-color: lightblue;
    height: auto;
    margin-top: 5px;
    padding: 20px 20px;
}
1
0
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
0