0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ゾンビでもわかるFlask入門-HTMLファイルを表示する

0
Last updated at Posted at 2026-06-30

前回(Docker環境編)で作ったDocker上のFlask最小構成を土台に、今回は文字列を返すだけだったルートを「HTMLファイルを表示する」ように拡張します。

ポイント:render_template と templates ディレクトリ

Flaskでは render_template("ファイル名") を使うと、templates/ ディレクトリの中にあるHTMLファイルを読み込んで返せます。この templates/ という名前は Flask の規約で決まっており、置き場所を変える必要はありません。

ディレクトリ構成

flask/
├── compose.yaml
├── Dockerfile
├── requirements.txt
├── app.py
└── templates/          ← 追加
    └── index.html      ← 追加

コード

app.py

from flask import Flask, render_template

# Flaskアプリケーションの本体を生成する
app = Flask(__name__)


# ルートURL("/")にアクセスされたときの処理
# templates/index.html を読み込んで返す
@app.route("/")
def index():
    return render_template("index.html")


if __name__ == "__main__":
    # 0.0.0.0 で待ち受けることでコンテナ外(ホスト)からアクセスできる
    app.run(host="0.0.0.0", port=5000, debug=True)

変更点は2つだけです。

  1. from flask import Flaskrender_template を追加
  2. 文字列 "Hello, World!" を返す代わりに render_template("index.html") を返す

templates/index.html

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>ゾンビハンティングクラブ</title>
</head>
<body>
    <h1>ゾンビでもわかるFlask入門</h1>
    <p>これは templates/index.html を表示しています。</p>
</body>
</html>

実行と確認

Docker環境はボリュームマウント+debugモードでホットリロードが効くので、ファイルを保存するだけで反映されます。コンテナを起動していない場合は次のコマンドで起動します。

docker compose up

確認:

$ curl -i http://localhost:5000/
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8

<!DOCTYPE html>
<html lang="ja">
...

ブラウザで http://localhost:5000 を開くと、index.html の見出しと本文が表示されます。

まとめ

  • render_template("xxx.html")templates/ 内のHTMLを返せる
  • templates/ はFlaskの規約のディレクトリ名なので固定
  • Docker環境のおかげで保存即反映、ビルドし直しも不要
  • 次回はHTMLからCSSとJavaScriptを読み込む(static/ ディレクトリ)予定
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?