【发布时间】:2020-05-05 08:41:28
【问题描述】:
假设我们有一个这样的基于 Bottle 的应用程序:
from bottle import route, run, request, template, response
import time
def long_processing_task(i):
time.sleep(0.5) # here some more
return int(i)+2 # complicated processing in reality
@route('/')
def index():
i = request.params.get('id', '', type=str)
a = long_processing_task(i)
response.set_header("Cache-Control", "public, max-age=3600") # does not seem to work
return template('Hello {{a}}', a=a) # here in reality it's: template('index.html', a=a, b=b, ...) based on an external template file
run(port=80)
显然要去http://localhost/?id=1、http://localhost/?id=2、http://localhost/?id=3等。 每页至少需要 500 毫秒第一次加载。
如何使这些页面的后续加载更快?
更准确地说,有没有办法两者兼得:
客户端缓存:如果用户A访问过http://localhost/?id=1一次,那么如果用户A第二次访问这个页面会更快
服务器端缓存:如果用户 A 访问过一次http://localhost/?id=1,那么如果 用户 B 稍后访问此页面(用户 B 是第一次!),它也会更快。
换句话说:如果花费 500 毫秒为一个用户生成 http://localhost/?id=1,它将被缓存以供 所有未来用户 请求相同的页面。 (有名字吗?)
?
注意事项:
在我的代码中
response.set_header("Cache-Control", "public, max-age=3600")似乎不起作用。-
this tutorial中提到了模板缓存:
模板在编译后缓存在内存中。在您清除模板缓存之前,对模板文件所做的修改不会产生任何影响。调用 bottle.TEMPLATES.clear() 这样做。缓存在调试模式下被禁用。
但我认为这与准备发送给客户端的最终页面的缓存无关。
- 我已经阅读了Python Bottle and Cache-Control,但这与静态文件有关。
【问题讨论】:
标签: python caching bottle cache-control