簡體   English   中英

Python瓶和緩存控制

[英]Python Bottle and Cache-Control

我有一個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上的Developer工具的標題時:我有Cache-Control:max-age=0Cache-Control:no-cache

我查看了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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM