Wel*_*lls 3 python jinja2 flask
我有这个:
{{ url_for('static', filename='css/main.min.css') }}
Run Code Online (Sandbox Code Playgroud)
但我在模板中也有一个时间戳,我想传递以防止缓存,例如:
{{ url_for('static', filename='css/main.min.css?timestamp=g.timestamp') }}
Run Code Online (Sandbox Code Playgroud)
这显然不起作用。HTML 需要最终阅读:
href="css/main.min.css?timestamp= 1440133238"
您可以使用类似此代码段的内容来覆盖url_for
静态文件的处理程序。
这是一个工作示例:
应用程序
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)
Run Code Online (Sandbox Code Playgroud)
模板/index.html
<html>
<body>
<img src="{{ url_for('static', filename='20110307082700.jpg') }}" />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
访问页面时,访问日志中会出现以下内容:
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 -
Run Code Online (Sandbox Code Playgroud)