2014-07-10 207 views
9

我有一個應用程序與Python瓶,我想添加緩存控制在靜態文件。如果我做錯了什麼,我對此很新,所以請原諒我。Python瓶和緩存控制

下面是函數,我如何提供靜態文件:

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

要添加緩存控制我已經包含了一個多線(我看到它的教程)

@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

+0

嘗試使用''response.set_header的(),而不是'response.headers'因爲他們在[文檔]說(HTTP:// bottlepy。組織/文檔的/ dev/tutorial.html?突顯=緩存控制)。像這樣''response.set_header('Cache-Control','max-age = 3600,public')' – doru

+0

@doru我已經嘗試過了,但是在Chrome開發者工具的網絡選項卡中我有同樣的事情(Cache-控制:最大年齡= 0)。並且每個靜態文件似乎都會在每次刷新時加載 – Sfinos

+0

請使用「wget」或「curl」代替Chrome,並讓我們知道您看到的內容。 –

回答

14

我看了source codestatic_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這裏沒有任何效果。

這確實preicesly你以後:

$ 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 
+1

對於那些想知道的,604800是一週內的秒數。 '604800/60/60/24 = 7'。好奇心有時候很奇怪。 – tleb