如何在GET
请求中设置适当的缓存标头?我想设置expires
和cache-control
,如下所示:
我的render_GET
看起来与此相似:
def render_GET(self, request):
data = self.getData(request) #dict
cache(request)
request.write(json.dumps(data))
request.finish()
我编写了以下缓存助手:
from wsgiref.handlers import format_date_time as format_date
from datetime import date, timedelta
from time import mktime
'''
Sets the cache headers for a (static resource) request
'''
def cache(request, expires=30, public=True):
#set expires header
expiry = (date.today() + timedelta(expires)).timetuple()
request.setHeader("expires" , format_date(mktime(expiry)))
cache_control = "max-age=" + str(60*60*24*expires)
if public:
cache_control += ", public"
else:
cache_control += ", private"
request.setHeader("cache-control", cache_control)
return request
但是,生成的响应标头不符合预期:
HTTP/1.1 200 OK
Content-Type: text/html
Date: Wed, 12 Mar 2014 13:03:04 GMT
Server: TwistedWeb/13.1.0
transfer-encoding: chunked
答案 0 :(得分:2)
看看你的要点和问题,你的要点是写完后cache
request.write(qjson.dumps(lang))
cache(request)
request.finish()
在写之前问题有cache
。
def render_GET(self, request):
data = self.getData(request) #dict
cache(request)
request.write(json.dumps(data))
request.finish()
最有可能的是,你的问题代码会起作用,但你的要点不会。但正如评论中指出的那样,这不是问题。
您没有设置Content-Length
标头。如果未设置Content-Length
标头,则使用分块编码来禁用缓存标头。
以下内容生成正确的响应标头
def render_GET(self, request):
data = json.dumps(self.getData(request)) #dict
request.setHeader('Content-Length', len(data))
cache(request)
request.write(data)
request.finish()
受到以下帖子http://msoulier.wordpress.com/2010/06/11/twisted-python-and-chunked-encoding/
的启发答案 1 :(得分:-1)
根据TwistedMatrix上的this bug report,我将request.setHeader()
切换为request.responseHeaders.setRawHeaders()
,如下所示:
def cache(request, expires=30, public=True):
#set expires header
expiry = (date.today() + timedelta(expires)).timetuple()
request.responseHeaders.setRawHeaders("expires" , [format_date(mktime(expiry))])
#set cache control
cache_control = "max-age=" + str(int(60*60*24*expires))
if public:
cache_control += ", public"
else:
cache_control += ", private"
request.responseHeaders.setRawHeaders("cache-control", [cache_control])
return request
正在投放的标头中的结果:
Accept-Ranges: bytes
Cache-Control: max-age=2592000, public
Connection: keep-alive
Content-Encoding: gzip
Content-length: 0
Date: Wed, 12 Mar 2014 16:18:57 GMT
Expires: Fri, 11 Apr 2014 00:00:00 GMT
Last-Modified: Wed, 12 Mar 2014 15:06:01 GMT
Server: TwistedWeb/13.1.0