Python Bottle 和缓存控制

标签 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 上的开发者工具检查 header 时:我有 Cache-Control:max-age=0Cache-Control:no-cache

最佳答案

我查看了 source code对于 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

关于Python Bottle 和缓存控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24672996/

相关文章:

python - Pandas groupby 类别,评级,从每个类别中获得最高值(value)?

image - 使用任意 QML 项作为缓存图像源

caching - 缓存集群部署拓扑

python 瓶: iterate through folder in app's route or in template?

python - 有没有办法让 Bottle 服务器不那么冗长?

regex - Nginx - 在 uwsgi_pass 之前重写 request_uri

python - 如果我使用 [LOGLEVEL],如何向 python 标准记录器添加对齐方式?

python - adfuller 测试收到 ValueError : too many values to unpack

python - einsums 的 numpy 组成?

c - 使用Intel的PIN工具来计算程序中缓存命中/未命中的次数