【Python/Flask】HTMLファイルの表示

Pythonモジュール「Flask」でHTMLファイルを表示する方法についてまとめました。

## HTMLファイルを表示

①以下のスクリプトを作成します。

■server.py

# -*- coding: utf-8 -*-
from flask import Flask, render_template

app = Flask(__name__)


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

def main():
    app.debug = True
    app.run(host='127.0.0.1', port=8080)

if __name__ == '__main__':
    main()

②プロジェクトフォルダ内に「templates」フォルダを作成します。

-- mysite
    -- templates
    -- server.py

③「templates」フォルダ内にHTMLファイル(index.html)を格納します。
■HTMLファイル(index.html)

<!DOCTYPE html>
<html lang="ja">
  <head>
  </head>
  <body>

    <h1>Hello World!</h1>

  </body>
</html>

■ディレクトリ構造

-- mysite
    -- templates
        -- index.html
    -- server.py

③スクリプトファイル(server.py)を実行します。

python mysite/server.py

※mysiteはプロジェクト名

④ブラウザで「http://127.0.0.1:8080」にアクセスしてHTMLファイルの内容が表示されたら成功です。

【Flask入門】簡単かつ効率的にWebアプリケーションを開発しよう
PythonとFlaskでWebアプリケーションを作る方法について入門者向けにまとめました。
Python
スポンサーリンク
西住工房

コメント