技術雑記帳兼日記帳

AWS、Python、Terraformの使い方をコッソリ

flask blueprintとsession

はじめに

今回はページをモジュール分割するのに便利なblueprintとsessionを解説する。
ページ構成は単純でログイン画面でID1とID2を入力して、その値をsessionで引き継いでpostページに表示するだけ。

準備

下記のファイルを作成する。

  • application.py
from flask import Flask
from login import loginPage
from post import postPage
app = Flask(__name__)

app.register_blueprint(loginPage)
app.register_blueprint(postPage)
app.secret_key = 'foobar'

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=80)
  • login.py
from flask import Blueprint, render_template, redirect, url_for, request, session
loginPage = Blueprint('loginPage', __name__, template_folder='templates')

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

@loginPage.route('/login_do', methods=['POST'])
def login_do():
    session['id1'] = request.form['id1']
    session['id2'] = request.form['id2']
     
    return redirect(url_for('postPage.post'))
  • post.py
from flask import Blueprint, render_template, session
postPage = Blueprint('postPage', __name__,template_folder='templates')

@postPage.route('/post')
def post():
    return render_template('post.html'
                            , msg1=session['id1']
                            , msg2=session['id2'])
  • login.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login</title>
</head>
<body>
  <form action="/login_do" accept-charset="UTF-8" method="post">
    <a>id1:    </a>
    <input type="text" name="id1"></input> <BR>
    <a>id2: </a>
    <input type="text" name="id2"></input> <BR>
    <input type="submit" name="submit"></input>
  </form>
</body>
</html>
  • post.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Welcome to post show page</title>
</head>

<body>
  <p>template Login</p> 
  <p>{{ msg1 }}</p>
  <p>{{ msg2 }}</p>
</body>

</html>

実行結果

f:id:halhalhal1:20210329202800p:plain

f:id:halhalhal1:20210329202818p:plain


まとめ

applicationモジュールでblueprint登録することで使用できる。
また、applicationに共通処理を記載できる。
例としては、Sessionのシークレットキーがそれに当たる。

app.secret_key = 'foobar'

しかし、いつもredirectでページ遷移させてるけど、正解がわからんな。 ボタンに持たせるのが正解?