用于标识出资源的状态。当资源发生变更时,如果其头信息中一个或者多个发生变化,或者消息实体发生变化,那么ETag也随之发生变化。
ETag常与If-None-Match或者If-Match一起,由客户端通过HTTP头信息(包括ETag值)发送给服务端处理。ETag使用如下:
request headers
......
If-None-Match: "3c64e7a072b3b57e100c96134e5ed2929e8dc56c"
......
response headers
HTTP/1.1 304 Not Modified
Date: Tue, 10 May 2016 06:29:05 GMT
Etag: "3c64e7a072b3b57e100c96134e5ed2929e8dc56c"
Server: TornadoServer/4.3
Tornado Etag 实现
根据请求的返回的数据_write_buffer,通过hashlib.sha1
算出etag
def compute_etag(self):
"""Computes the etag header to be used for this request.
By default uses a hash of the content written so far.
May be overridden to provide custom etag implementations,
or may return None to disable tornado‘s default etag support.
"""
hasher = hashlib.sha1()
for part in self._write_buffer:
hasher.update(part)
return ‘"%s"‘ % hasher.hexdigest()
通过request
.headers
的If-None-Match"
获取上一次的etag和这次的etag比较
def check_etag_header(self):
"""Checks the ``Etag`` header against requests‘s ``If-None-Match``.
Returns ``True`` if the request‘s Etag matches and a 304 should be
returned. For example::
self.set_etag_header()
if self.check_etag_header():
self.set_status(304)
return
This method is called automatically when the request is finished,
but may be called earlier for applications that override
`compute_etag` and want to do an early check for ``If-None-Match``
before completing the request. The ``Etag`` header should be set
(perhaps with `set_etag_header`) before calling this method.
"""
computed_etag = utf8(self._headers.get("Etag", ""))
# Find all weak and strong etag values from If-None-Match header
# because RFC 7232 allows multiple etag values in a single header.
etags = re.findall(
br‘\*|(?:W/)?"[^"]*"‘,
utf8(self.request.headers.get("If-None-Match", ""))
)
if not computed_etag or not etags:
return False
match = False
if etags[0] == b‘*‘:
match = True
else:
# Use a weak comparison when comparing entity-tags.
val = lambda x: x[2:] if x.startswith(b‘W/‘) else x
for etag in etags:
if val(etag) == val(computed_etag):
match = True
break
return match
如果一样说明没改变,不返还内容只返回304
......
if self.check_etag_header():
self._write_buffer = []
self.set_status(304)
......
时间: 2024-09-30 23:34:14