LoginSignup
17
15

More than 5 years have passed since last update.

静的ファイルの更新がブラウザのキャッシュで反映されない問題の対策

Posted at

chrome.png

javascriptやstylesheet、または上記のような画像ファイルを静的ファイルとして公開し、それを参照する場合
ブラウザのキャッシュによってサーバー上は更新されても表示が反映されないという問題に
度々ひっかかる。

この対策方法の一つとしてファイルのurlの最後に?q=<ファイルの更新日時>などとして
ファイルの更新日時を付与する方法がある。

Flaskではこうするといいよというスペニットがあったので紹介する。

具体的なコード

app.pyoverride_url_for()dated_url_for()
静的ファイルに対して?q=<ファイルの更新日時>を付与するコードを作っている。

index.htmlsrc="{{url_for('static', filename='img/20180926_0900_toyo_vs_suga.png')}}"でそれが展開されるという仕組み。

app.py
from flask import Flask, render_template, url_for
import os

app = Flask(__name__)

@app.context_processor
def override_url_for():
    return dict(url_for=dated_url_for)

def dated_url_for(endpoint, **values):
    if endpoint == 'static':
        filename = values.get('filename', None)
        if filename:
            file_path = os.path.join(app.root_path,
                                     endpoint, filename)
            values['q'] = int(os.stat(file_path).st_mtime)
    return url_for(endpoint, **values)

@app.route('/')
def index():
    # index.html をレンダリングする
    return render_template('index.html')

if __name__ == '__main__':
    app.run()
layout.html
<!doctype html>
<html lang="ja">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

      {% if title %}
        <title>Hello, world!</title>
      {% else %}
        <title>Bootstrap 4.1.3 Template</title>
      {% endif %}
  </head>
  <body>
    {% block content %}{% endblock %}
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
  </body>
</html>
index.html
{% extends "layout.html" %}
{% block content %}

    <img src="{{url_for('static', filename='img/20180926_0900_toyo_vs_suga.png')}}" class="img-fluid" alt="Responsive image">

{% endblock %}

参考

FlaskでCSSのキャッシュを効かせなくする方法 - Life is Really Short, Have Your Life!!

static url cache buster | Flask (A Python Microframework)

17
15
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
17
15