【问题标题】:Python Bottle and Cache-ControlPython 瓶和缓存控制
【发布时间】:2014-08-31 14:51:27
【问题描述】:

我有一个带有 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

【问题讨论】:

  • 尝试使用response.set_header() 而不是response.headers,正如他们在docs 中所说的那样。像这样response.set_header('Cache-Control', 'max-age=3600,public')
  • @doru 我已经尝试过了,但是在 Chrome 开发者工具的网络选项卡中我有同样的东西(缓存控制:max-age=0)。每个静态文件似乎都会在每次刷新时加载
  • 请尝试使用wgetcurl 而不是Chrome,让我们知道您看到了什么。
  • @ron.rothman 我没有 wget 也没有卷曲。我通过 Python 和 urllib2 发出了 Headers 请求,结果如下:{'date': 'Fri, 11 Jul 2014 22:39:58 GMT', 'content-length': '30458', 'content-type': 'text/html; charset=UTF-8', 'server': 'WSGIServer/0.1 Python/2.7.6'}
  • 您是否注意到您的回复中没有 Cache-control 标头?

标签: python caching bottle


【解决方案1】:

我查看了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 的修改在这里没有任何效果。

这正是你所追求的:

$ 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

【讨论】:

  • 对于那些想知道的人来说,604800 是一周中的秒数。 604800 / 60 / 60 / 24 = 7。有时候,好奇心很奇怪。
猜你喜欢
  • 2012-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-30
  • 2016-01-03
  • 2020-09-22
  • 2012-06-06
  • 1970-01-01
相关资源
最近更新 更多