3

I have this:

{{ url_for('static', filename='css/main.min.css') }}

But I also have a timestamp in the template I would like to pass to prevent caching, like:

{{ url_for('static', filename='css/main.min.css?timestamp=g.timestamp') }}

Which obviously doesn't work. The HTML needs to end up reading:

href="css/main.min.css?timestamp= 1440133238"

1 Answer 1

5

You could use something like this snippet to override the url_for handler for static files.

Here's a working example:

app.py

from flask import Flask, render_template, request, url_for
import os

app = Flask(__name__)
app.debug=True

@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():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(port=5000)

templates/index.html

<html>
<body>
<img src="{{ url_for('static', filename='20110307082700.jpg') }}" />
</body>
</html>

When the page is accessed, the following appears in the access log:

127.0.0.1 - - [21/Aug/2015 13:24:55] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [21/Aug/2015 13:24:55] "GET /static/20110307082700.jpg?q=1422512336 HTTP/1.1" 200 -
Sign up to request clarification or add additional context in comments.

1 Comment

huh, that's a little messier than I was hoping for, but certainly seems to work-- thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.