WEBアプリケーションを作る2ーFlask編
どうもhiroakiです。
Flaskを使ったWEBアプリケーションを作る方法を紹介します。前回の続きになりますので、前回の記事もご参考ください。HTMLとCSSについては以下を参考ください。
テンプレートでループする
ここではページ上でループを行います。
- < -- templatesファイル内のindex.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>選択 - くじ引き</title>
- </head>
- <body>
- <h1>くじ引き</h1>
- <p>番号を選んで果物を受け取りましょう。</p>
- {% for a_day in week %}
- <h3>{{ a_day }}</h3>
- {% endfor %}
- </body>
- </html>
- from flask import Flask, render_template
- app = Flask(__name__)
- @app.route("/")
- def index():
- week = ['月', '火', '水', '木', '金']
- duties = {'月': '佐藤', '火': '鈴木', '水': '清水', '木': '中村', '金': '高橋'}
- return render_template('index.html', week=week)
HTMLのfor文は、Jinja2のテンプレートエンジンの構文です。Pythonのfor文と同じようにリストのデータを列挙できます。{% for a_day in week %} から {% endfor %} の間の処理がリスト week の要素の数分、実行されます。{% endfor %} を忘れないように注意してください。
クエリストリングについて
クエリストリング(QueryString)とは、Webサーバーに追加で情報を与えるためにURLに付け加える情報です。コンテキストパスに続けて ? を書き、続けて key=value 形式でデータを書きます。
Google で Python と入力し検索結果が表示されている画面の URL を見てください。
?q=Python の部分がクエリストリングです。キーと値を = で結合し指定します。
- < -- templatesファイル内のresult.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>結果 - くじ引き</title>
- </head>
- <body>
- <h1>結果</h1>
- <p><strong> {{ fruit }} </strong>が当たりました。</p>
- <p><a href="/">戻る</a></p>
- </body>
- </html>
- from flask import Flask, render_template, request
- app = Flask(__name__)
- @app.route("/")
- def index():
- return render_template('index.html')
- @app.route("/result")
- def result():
- fruits = {'1': 'もも', '2': 'りんご', '3': 'みかん'}
- # 値を受け取る
- fruit_no=request.args.get('fruit_no','')
- return render_template('result.html',fruit=fruits[fruit_no])
request.args.get('fruit_no', '')はrequest.args['fruit_no']としても値を取り出せます。request.args.get('fruit_no', '')の第2引数に空の文字列が指定されているのはfruit_noが取得できなかった場合のデフォルト値を指定しています。これで、値によって表示結果が変わります。
画面からデータを引き継ぐ
次に、画面で入力されたデータを表示させましょう。まず、templatesフォルダ内にinput.htmlとoutout.htmlファイルを用意します。
- < -- templatesファイル内のinput.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>お名前を入力して下さい</title>
- </head>
- <body>
- <form method="get" action="/output">
- <p>名前:<input type="text" name="name" size="40">
- </p>
- <button type="submit">送信</button>
- </form>
- </body>
- </html>
- < -- templatesファイル内のoutput.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>お名前の表示</title>
- </head>
- <body>
- <h1>入力された名前は「{{ name }}」です</h1>
- <p><a href="/">戻る</a></p>
- </body>
- </html>
- from flask import Flask, render_template, request
- app = Flask(__name__)
- @app.route("/")
- def index():
- return render_template('input.html')
- @app.route("/output")
- def output():
- your_name =request.args.get('name','')
- return render_template('output.html',name=your_name)
▼input.html
▼output.html
<form>タグは画面から動的にデータを受け取るために利用します。
action属性には、上記のように送信先のURLを指定します。他にも、Flask の関数であるurl_for関数を指定できます。url_forの引数に関数名を入れると、routeメソッドで指定されたアドレスが戻り値になります。例えば上記/outputの代わりに、{{ url_for('output')}}と指定すれば、output関数を呼び出すアドレスが出力されます。
method属性には「データの送信方法」を指定します。データの送信方法には、GETとPOSTがあります。
GETはサーバーからデータを取得するために使います。URLの末尾で取得したいデータ(検索条件など)を?name=hogeのように指定します。さきほど、GoogleでPythonと検索した場合を思い出してみてください。
POSTはサーバーにデータを送信するために使います。送信するデータはURLに表示されません。
また、Pythonが裏で動いているので入力を受け取るような動的なページを作れるんですね。
今回は以上です。何度も繰り返して理解しましょう。
次回も続きをやっていきますので、不明点等ありましたら、気軽にコメントください。一緒に頑張りましょう。
では。