Python Bottle 与 Cache-Control

11 投票
1 回答
5628 浏览
提问于 2025-04-18 12:46

我有一个用Python Bottle做的应用程序,我想在静态文件中添加Cache-Control。因为我刚接触这个,所以如果我做错了什么,请多包涵。

这是我用来提供静态文件的函数:

@bottle.get('/static/js/<filename:re:.*\.js>')
def javascripts(filename):
   return bottle.static_file(filename, root='./static/js/')

为了添加Cache-Control,我又加了一行代码(我是在一个教程里看到的)

@bottle.get('/static/js/<filename:re:.*\.js>')
def javascripts(filename):
   bottle.response.headers['Cache-Control'] = 'public, max-age=604800'
   return bottle.static_file(filename, root='./static/js/')

但是当我在Chrome的开发者工具中查看响应头时,我看到的要么是 Cache-Control:max-age=0,要么是 Cache-Control:no-cache

1 个回答

22

我查看了static_file()的源代码,找到了问题的解决办法。

你需要把static_file(...)的结果赋值给一个变量,然后在这个得到的HTTPResponse对象上调用set_header()

#!/usr/bin/env python

import bottle


@bottle.get("/static/js/<filename:re:.*\.js>")
def javascripts(filename):
    response = bottle.static_file(filename, root="./static/js/")
    response.set_header("Cache-Control", "public, max-age=604800")
    return response

bottle.run(host="localhost", port=8000, debug=True)

简单来说,static_file(...)会创建一个全新的HTTPResponse对象,而你对bottle.response的修改在这里是没有效果的。

这正是你想要的效果:

$ curl -v -o - http://localhost:8000/static/js/test.js
* Adding handle: conn: 0x7f8ffa003a00
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x7f8ffa003a00) send_pipe: 1, recv_pipe: 0
* About to connect() to localhost port 8000 (#0)
*   Trying ::1...
*   Trying fe80::1...
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8000 (#0)
> GET /static/js/test.js HTTP/1.1
> User-Agent: curl/7.30.0
> Host: localhost:8000
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Date: Tue, 15 Jul 2014 00:19:11 GMT
< Server: WSGIServer/0.1 Python/2.7.6
< Last-Modified: Tue, 15 Jul 2014 00:07:22 GMT
< Content-Length: 69
< Content-Type: application/javascript
< Accept-Ranges: bytes
< Cache-Control: public, max-age=604800
<
$(document).ready(function () {
    console.log("Hello World!");
});
* Closing connection 0

撰写回答