Flaskは、最小限のコンポーネントで柔軟にWebアプリを構築できるマイクロフレームワークです。
ルーティングとパラメータの取得
Python
from flask import Flask, request, render_template, redirect, url_for, flash, session
app = Flask(__name__)
app.secret_key = "super_secret_key" # セッション暗号化用キー
# 動的URLパラメータ
@app.route("/user/<int:user_id>")
def show_user(user_id):
return f"ユーザーID: {user_id}"
# クエリパラメータの取得 (/search?q=python)
@app.route("/search")
def search():
query = request.args.get("q", "")
return f"検索ワード: {query}"
Jinja2テンプレートエンジンによる動的レンダリング
Python側のデータをHTMLテンプレートへ渡して表示します。
HTML
<!-- templates/users.html -->
<!DOCTYPE html>
<html lang="ja">
<body>
<h1>ユーザー一覧</h1>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for msg in messages %}
<li>{{ msg }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<ul>
{% for user in users %}
<li>{{ user.name }} - {{ user.role }}</li>
{% endfor %}
</ul>
</body>
</html>
セッションとフラッシュメッセージ
Python
@app.route("/login", methods=["POST"])
def login():
username = request.form.get("username")
session["user"] = username # 状態の保持
flash("ログインに成功しました!") # 一度だけ表示される通知メッセージ
return redirect(url_for("dashboard"))

コメント