Flaskのテンプレート捜索をログに出力する

Application ObjectEXPLAIN_TEMPLATE_LOADINGTrue に設定すると、 render_template を使ったときに実際にどのテンプレートが対象とされるかを調べることができます。

jinja2.exceptions.TemplateNotFound となった場合にちょっと便利です。

小さいアプリで実験しましょう。

公式ドキュメント

EXPLAIN_TEMPLATE_LOADING¶ Configuration Handling — Flask Documentation (1.1.x)

命名がとてもストレートで嬉しいですね。

環境条件

$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.15.4
BuildVersion:   19E287

$ flask --version
Python 3.8.4
Flask 1.1.2
Werkzeug 1.0.1

実験

今回は2つのパターンで検証します。 (:memo: Blueprint を使った場合はまた今度)

  1. 正しくtemplateが見つかる場合(index())
  2. templateが存在しない場合(not_exist_template)

ログに着目しましょう。

実験用ソースコード

ソースコードhttps://github.com/mohira/flask-blog/tree/master/explain_template_loading にあります。

# ディレクトリ構成
$ tree explain_template_loading

explain_template_loading
├── __init__.py
├── app.py
└── templates
    └── index.html
from flask import Flask, render_template

app = Flask(__name__)
app.config['EXPLAIN_TEMPLATE_LOADING'] = True


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


@app.route('/not_exist')
def not_exist_template():
    return render_template('not_exist.html')  # わざと用意していない


def main():
    app.run(debug=True)


if __name__ == '__main__':
    main()

index.html はわかりやすいようにファイルのパスを書いています。

<h1>Hello from /templates/index.html</h1>

実験1. 正しくtemplateが見つかる場合(index())

$ curl http://127.0.0.1:5000/
<h1>Hello from /templates/index.html</h1>
[2020-07-22 09:58:00,675] INFO in debughelpers: Locating template "index.html":
    1: trying loader of application "__main__"
       class: jinja2.loaders.FileSystemLoader
       encoding: 'utf-8'
       followlinks: False
       searchpath:
         - /Users/your_home/mob-mob-blog/explain_template_loading/templates
       -> found ('/Users/your_home/mob-mob-blog/explain_template_loading/templates/index.html')

127.0.0.1 - - [22/Jul/2020 09:58:00] "GET / HTTP/1.1" 200 -

index.html という template を /Users/your_home/mob-mob-blog/explain_template_loading/templates という searchpath から検索していることがわかりますね。

実験2. templateが存在しない場合(not_exist_template())

$ curl http://127.0.0.1:5000/not_exist
# 表示されるデバッグ情報は省略
[2020-07-22 10:00:00,301] INFO in debughelpers: Locating template "not_exist.html":
    1: trying loader of application "__main__"
       class: jinja2.loaders.FileSystemLoader
       encoding: 'utf-8'
       followlinks: False
       searchpath:
         - /Users/your_home/mob-mob-blog/explain_template_loading/templates
       -> no match
Error: the template could not be found.

127.0.0.1 - - [22/Jul/2020 10:00:00] "GET /not_exist HTTP/1.1" 500 -

Traceback (most recent call last):
# 細かいTraceBackは省略
# ...
jinja2.exceptions.TemplateNotFound: not_exist.html

not_exist.html という template を /Users/your_home/mob-mob-blog/explain_template_loading/templates という searchpath から検索していることがわかりますね。

しかし、実験1と違い、templateがないので no match となっていますね。