本文主要是介绍Etag 笔记,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
用于标识出资源的状态。当资源发生变更时,如果其头信息中一个或者多个发生变化,或者消息实体发生变化,那么ETag也随之发生变化。
ETag常与If-None-Match或者If-Match一起,由客户端通过HTTP头信息(包括ETag值)发送给服务端处理。ETag使用如下:
request headers
......
If-None-Match: "3c64e7a072b3b57e100c96134e5ed2929e8dc56c"
......
response headers
HTTP/1.1 304 Not ModifiedDate: Tue, 10 May 2016 06:29:05 GMTEtag: "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 bereturned. For example::self.set_etag_header()if self.check_etag_header():self.set_status(304)returnThis 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 Falsematch = Falseif etags[0] == b'*':match = Trueelse:# Use a weak comparison when comparing entity-tags.val = lambda x: x[2:] if x.startswith(b'W/') else xfor etag in etags:if val(etag) == val(computed_etag):match = Truebreakreturn match
如果一样说明没改变,不返还内容只返回304
......
if self.check_etag_header():self._write_buffer = []self.set_status(304)
......
这篇关于Etag 笔记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!