Etag 笔记

用于标识出资源的状态。当资源发生变更时,如果其头信息中一个或者多个发生变化,或者消息实体发生变化,那么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.headersIf-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)
......
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值