如何修改CSV文件后让PyScript+Bottle应用实时更新数据?
解决PyScript+Bottle中修改CSV后无法自动加载最新数据的问题
问题根源
Bottle的static_file默认会给静态资源添加缓存头,浏览器会将CSV这类文件存入本地缓存,修改后浏览器直接读取缓存副本,不会主动从服务器获取最新数据。debug=True仅负责自动重载修改后的Python代码,不会影响静态文件的缓存策略。
解决方案
给静态文件(尤其是data目录下的CSV)添加禁用缓存的响应头,强制浏览器每次请求都从服务器拉取最新文件。以下两种方法任选:
方法1:单独给data目录的文件设置缓存头
直接修改data路由的static_file调用,添加headers参数:
@route("/data/<file_name:path>") def data_files(file_name): return static_file( file_name, root=f"data/", headers={ "Cache-Control": "no-cache, no-store, must-revalidate", "Pragma": "no-cache", "Expires": "0" } )
这些响应头会告诉浏览器:
- 不能直接使用缓存,必须先与服务器确认资源是否更新
- 禁止存储任何版本的资源缓存
- 缓存立即过期
方法2:全局禁用所有静态文件缓存
如果希望所有静态资源都不被缓存,可以写一个装饰器统一处理:
from bottle import route, static_file, response def no_cache(func): def wrapper(*args, **kwargs): response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" response.headers["Pragma"] = "no-cache" response.headers["Expires"] = "0" return func(*args, **kwargs) return wrapper # 给所有静态路由添加该装饰器 @route("/<file_name:path>") @no_cache def static_files(file_name): return static_file(file_name, root=f"./") @route("/images/<file_name:path>") @no_cache def images_files(file_name): return static_file(file_name, root=f"images/") # 其他静态路由同理添加@no_cache装饰器
修改后的完整代码
from bottle import route, post, request, run, template, static_file @route("/") def main_page(): return static_file("WES1.html", root=f"./") @route("/<file_name:path>") def static_files(file_name): return static_file(file_name, root=f"./") @route("/images/<file_name:path>") def images_files(file_name): return static_file(file_name, root=f"images/") @route("/static/<file_name:path>") def static_files(file_name): return static_file(file_name, root=f"static/") @route("/data/<file_name:path>") def data_files(file_name): return static_file( file_name, root=f"data/", headers={ "Cache-Control": "no-cache, no-store, must-revalidate", "Pragma": "no-cache", "Expires": "0" } ) @route("/src/<file_name:path>") def source_files(file_name): return static_file(file_name, root=f"src/") run(host='localhost', port=8080, debug=True)
额外提示
Bottle.reset()是无效的,Bottle框架没有这个方法,因此会报错,无需使用。- 如果只想针对CSV文件生效,可以在data路由中添加后缀判断,仅给
.csv文件设置缓存头:
@route("/data/<file_name:path>") def data_files(file_name): headers = {} if file_name.endswith(".csv"): headers = { "Cache-Control": "no-cache, no-store, must-revalidate", "Pragma": "no-cache", "Expires": "0" } return static_file(file_name, root=f"data/", headers=headers)
内容的提问来源于stack exchange,提问作者Erick
相关产品推荐
相关产品推荐

