摘要

  博主在使用flask进行web开发时,需要将图片上传并展示,对于上传的图片都进行重命名并保存在static文件夹下,然而发现多次上传后展示的图片还是原来的图片,尽管后端显示图片已更新成最新上传的图片,前端还是展示原来的图片,本篇将提供解决方法。

解决办法

  博主在网络上找到两类解决办法,其中一类是修改静态文件的缓存时间为1秒,然而亲测无效。

# 设置静态文件缓存过期时间
app.send_file_max_age_default = timedelta(seconds=1)

  另一类是通过重写url_for的方法,注意前端也要通过url_for访问静态资源,亲测有效。

# url_for,修改静态文件(js,css,image)时,网页同步修改
@app.context_processor
def override_url_for():
    return dict(url_for=dated_url_for)


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

以上。

相关文章:

  • 2022-12-23
  • 2022-02-08
  • 2021-09-05
  • 2021-06-24
  • 2022-01-29
  • 2021-11-23
  • 2021-06-20
  • 2022-12-23
猜你喜欢
  • 2021-08-29
  • 2021-08-18
  • 2021-08-07
  • 2022-12-23
  • 2022-01-07
  • 2022-01-08
相关资源
相似解决方案