LoginSignup
0
0

Flask で、templates と static 以下のファイルをキャッシュされないようにする

Posted at

背景

Python + Flask で簡単な Web アプリを開発していたのですが、

  • templates 以下の html ファイルを更新しても、プログラムを再起動しないと反映されない
  • static 以下の css やスクリプトも同様

となってしまい、開発効率がすこぶる悪かったので、なんとかしたいのが発端でした。

環境

  • macOS Ventura
  • Python 3.11.4
  • Flask==2.3.2

調査

static 以下のファイルについてはこちらの方法でうまく行きました。:pray:

app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0

ところが templates 以下はまた別の設定が必要なようです。色々探した結果、見つけたのはこちら。

app.config['TEMPLATES_AUTO_RELOAD'] = True

結果

シンプルな app.py を例にするとこんな感じです。

app.py
from flask import Flask, render_template

PORT = 5000

app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0

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

if __name__ == "__main__":
    app.run(port=PORT)

無事、Flask を動かしつつ、html | css | script を修正してはチェックの繰り返しが効率よくできるようになりました。

参考

:point_up:もしかしたら、開発中はちゃんと DEBUG モードを有効しなさいよ、と言うことかもしれません。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0