price_flask.py #4 inja2について
【jija2 を使ってhtmlに表示させる】
そもそもjija2って何よ? pythonで使われているテンプレートエンジンって言うものでデータをhtmlに飛ばしてくれるもの。 名前の由来は、テンプレート ⇒ テンプル ⇒ 神社、との事。以下は、jinja2を使ってテーブルを作成しているところです。
price_table.py
<table id="datatable-buttons" class="table table-striped table-bordered">
<thead>
<tr>
<th>Last</th>
<th>Ask</th>
<th>High</th>
<th>Low</th>
<th>Volume</th>
<th>Timestamp</th>
</tr>
</thead>
<tbody>
{% for row in rows %}
<tr>
<td>{{row["last"]}}</td>
<td>{{row["ask"]}}</td>
<td>{{row["high"]}}</td>
<td>{{row["low"]}}</td>
<td>{{row["volume"]}}</td>
<td>{{row["datetime"]}}</td>
</tr>
{% endfor %}
</tbody>
</table>
順番としては
- template.txt.j2をテンプレートとして取得
- テンプレートに記述されている かっこを{{}} に値()を突っ込む
- 値を突っ込んだ結果を一番最後の行にあるコードでレンダリングして表示 この部分
return render_template('index.html')
#/indexにアクセスが来たらtemplates内のindex.htmlが開きます
【ポイント】
かっこよく言うと、サーバーサイドからクライアントサイドへmessageを渡す。
render_template('index.html', message=message)
上記の奇術の場合はindex.htmlを読み込む際にmessageという変数を渡すという意味になります。 html側では以下の通りになっている。
<div class="header">
{% if message %}
<p>{{message}}</p>
{% endif %}
</div>
【さらに詳しくjinja2 辞書型の変数を渡す編】
app.py
@app.route("/index")
def index():
my_dic = {}
my_dic['name'] = ryo2851
my_dic['univ'] = 'hogehoge University'
return render_template('index.html', message=my_dic)
index.html
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">Sample Page</h3>
{% if message %}
<p>name: {{message.name}}</p>
<p>univ: {{message.univ}}</p>
{% endif %}
</div>
</div>
</body>
htmlを読み込む際にmessageと言う変数を渡します。 messageがあったらmy_dict渡せってapp.pyのレンダリングの所に書いてある(message=my_dic)のでmessge変数を渡す。html部分をよく見ると、{message.name}となっている。つまり、my_dicのnameを渡すってこと。
今回自分で作ったprice_table.htmlでは{% for row in rows %}となっている。 つまり、rowと言う変数を渡せってこと。そして、row["last"]なのでrowの中でもlastとか指定したものを渡せってこと担っている。
<tbody>
{% for row in rows %}
<tr>
<td>{{row["last"]}}</td>
</tr>
{% endfor %}
【まとめ】
①sqlite3のデータベースに接続する
②flaskの構文で@app.route('/price')とあるのでlocalhost/priceにアクセする
③price_flask.pyの最後が return render_template("price_table.html",rows = rows, なのでrowsデータを飛ばす
④price_table.htmlに{% for row in rows %}
参考:
Jinja2の使い方がわかるとFlaskを用いた開発がよりスマートになる - Qiita
sqlite3:https://docs.python.jp/3/library/sqlite3.html