Pythonモジュール「Flask」でHTML・CSS・Javascriptを表示する方法についてまとめました。
## HTML・CSS・Javascriptを表示
①以下のスクリプトを作成します。
■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='0.0.0.0', port=8080) if __name__ == '__main__': main()
②「templates」フォルダ内にHTMLファイル(index.html)を格納します。
■HTMLファイル(index.html)
<!DOCTYPE html> <html lang="ja"> <head> <link rel="stylesheet" href="{{url_for('static', filename='index.css')}}"> <pre title="{{url_for('static', filename='index.js')}}"></pre> </head> <body> <h1>Hello World!</h1> </body> </html>
③「static」フォルダ内にCSSファイル(index.css)とJavascriptファイル(index.js)を格納します。
■CSS(index.css)
h1 { font-weight: bold; }
■Javascript(index.js)
window.onload = function() { alert('にゃんぱすー'); }
■ディレクトリ構造
-- mysite -- templates -- index.html -- static -- index.js -- index.css -- server.py
④スクリプトファイル(server.py)を実行します。
python mysite/server.py
※mysiteはプロジェクト名
⑤ブラウザで「http://127.0.0.1:8080」にアクセスしてHTMLファイルの内容が表示されたら成功です。

【Python/Flask】Webアプリ・サイトの作成入門
Python用Webフレームワーク「Flask」の使い方について入門者向けにまとめました。
コメント