def check_freshness(request, mtime=None, etag=None, weak=0):
cfg = request.cfg
# See if we are supposed to disable etags (for debugging, usually)
if not cfg.options.generate_etags:
return 0
request_etag = request_mtime = None
if etag is not None:
if weak:
etag = 'W/"%s"' % etag
else:
etag = '"%s"' % etag
request_etag = request.server.getenv('HTTP_IF_NONE_MATCH')
if mtime is not None:
try:
request_mtime = request.server.getenv('HTTP_IF_MODIFIED_SINCE')
request_mtime = rfc822.mktime_tz(rfc822.parsedate_tz(request_mtime))
except:
request_mtime = None
# if we have an etag, use that for freshness checking.
# if not available, then we use the last-modified time.
# if not available, then the document isn't fresh.
if etag is not None:
isfresh = (request_etag == etag)
elif mtime is not None:
isfresh = (request_mtime >= mtime)
else:
isfresh = 0
# require revalidation after the configured amount of time
if cfg and cfg.options.http_expiration_time >= 0:
expiration = rfc822.formatdate(time.time() +
cfg.options.http_expiration_time)
request.server.addheader('Expires', expiration)
request.server.addheader('Cache-Control',
'max-age=%d' % cfg.options.http_expiration_time)
if isfresh:
request.server.header(status='304 Not Modified')
else:
if etag is not None:
request.server.addheader('ETag', etag)
if mtime is not None:
request.server.addheader('Last-Modified', rfc822.formatdate(mtime))
return isfresh
评论列表
文章目录