Flask显示图片并设置图片的缓存时间

1.显示图片

想要Flask在网页中显示图片,需要使用template 模板,例如
index.py

from flask import Flask, render_template, url_for
app = Flask(__name__)
@app.route('/', methods=['GET'])
def hello_world():
    return render_template('index.html')
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=4000, debug=True)

index.html:

<html><head></head><body>
<img src="{{url_for('static', filename='xxx.jpg')}}" alt="图片" />
 </body></html>

图片需要放在static目录下,目录树如下:
tree

2.设置缓存时间

Flask的css,js,jpg等文件的默认缓存时间设置是12小时,所以经常图片更新了,但刷新网页后还是同一张图片,解决方案如下:

from datetime import timedelta
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=60) 
 # 设置图片的缓存时间为1分钟

具体的缓存时间可以视情况设定。

参考资料:
Flask上传本地图片并在页面上显示
Flask 静态文件缓存问题

猜你喜欢

转载自blog.csdn.net/zhangpeterx/article/details/83651261
今日推荐