Python瓶和缓存控制

时间:2014-07-10 09:31:44

标签: python caching bottle

我有一个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=0Cache-Control:no-cache

1 个答案:

答案 0 :(得分:15)

我查看了static_file()的{​​{3}}并找到了解决方案。

您需要将static_file(...)的结果分配给变量,并在生成的set_header()对象上调用HTTPResponse

#!/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