Python Flask ちょっとしたWebアプリケーション
Python と Flask を使って簡易なWebアプリケーションを作成してみた。
環境
手順
Flask と jinja2 をインストールしておく。
> pip install flask jinja2
フォルダ構成は下記の通り。
src ├ static │ └ css │ └ bootstrap.min.css ├ templates │ ├ base.html │ ├ home.html │ └ jump.html └ app.py
bootstrap.min.css
をダウンロードする。
https://getbootstrap.com/docs/4.0/getting-started/download/
app.py
を作成し、下記のコードをコピーアンドペーストする。
from flask import Flask from flask import request from flask import render_template app = Flask(__name__) @app.route('/', methods=["GET"]) def home(): return render_template('home.html') @app.route('/jump', methods=["POST"]) def test(): res: str = '' if request.method == 'POST': res = request.form['post_value'] return render_template('jump.html', res=res) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
base.html
を作成し、下記のコードをコピーアンドペーストする。
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>Jinja2 Tutorial</title> <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet"> </head> <body> <div class="navbar navbar-dark bg-dark box-shadow"> <div class="container d-flex justify-content-between"> <a class="navbar-brand" href="{{ url_for('home')}}">Jinja2 Tutorial</a> </div> </div> <div class="container"> {% block container %} {% endblock %} </div> </body> </html>
home.html
を作成し、下記のコードをコピーアンドペーストする。
{% extends "base.html" %} {% block container %} <h2>hello world !!</h2> <br> <form action="/jump" method="post"> <input name="post_value" type=text/> <button name="post_button">post submit</button> </form> {% endblock %}
jump.html
を作成し、下記のコードをコピーアンドペーストする。
{% extends "base.html" %} {% block container %} {{res}} {% endblock %}
動作確認
Flask を起動する。
> flask run
localhost:5000
へWebブラウザでアクセスする。
テキストボックスに適当な値を入力し、ボタンを押下する。
入力した値が画面に表示されることを確認する。
終わりに
簡単なWebアプリケーションを作成することができた。
画面項目を増やしたりして、もう少しできることを増やしていこうと思う。