def generate_cache_key( request: Request, method: str, varying_headers: typing.List[str], cache: Cache, ) -> str: """ Return a cache key generated from the request full URL and varying response headers. Note that the given `method` may be different from that of the request, e.g. because we're trying to find a response cached from a previous GET request while this one is a HEAD request. (This is OK because web servers will strip content from responses to a HEAD request before sending them on the wire.) """ assert method in CACHABLE_METHODS ctx = hashlib.md5() for header in varying_headers: value = request.headers.get(header) if value is not None: ctx.update(value.encode()) absolute_url = str(request.url) url = hashlib.md5(absolute_url.encode("ascii")) return cache.make_key( f"cache_page.{method}.{url.hexdigest()}.{ctx.hexdigest()}")
def generate_varying_headers_cache_key(request: Request, cache: Cache) -> str: """ Return a cache key generated from the requested absolute URL, suitable for associating varying headers to a requested URL. """ url = request.url.path url_hash = hashlib.md5(url.encode("ascii")) return cache.make_key(f"varying_headers.{url_hash.hexdigest()}")
def test_cache_version_kwarg_overrides_version_set_in_url(): cache = Cache("dummy://null?version=2019", version="2020") key = cache.make_key("test") assert "2019" not in key assert "2020" in key assert "test" in key
def test_cache_key_prefix_kwarg_overrides_key_prefix_be_set_in_url(): cache = Cache("dummy://null?key_prefix=prod", key_prefix="beta") key = cache.make_key("test") assert key.startswith("beta") assert "prod" not in key assert "test" in key
def test_cache_version_can_be_set_in_url(): cache = Cache("dummy://null?version=2019") key = cache.make_key("test") assert "2019" in key assert "test" in key
def test_cache_key_prefix_can_be_set_in_url(): cache = Cache("dummy://null?key_prefix=prod") key = cache.make_key("test") assert key.startswith("prod") assert "test" in key
def test_cache_created_key_includes_prefix_and_version(): cache = Cache("dummy://null", key_prefix="prod", version="2019") key = cache.make_key("test") assert key.startswith("prod") assert "2019" in key assert "test" in key
def test_cache_key_default_version_can_be_overridded(): cache = Cache("dummy://null", version="beta") key = cache.make_key("test", "custom") assert "beta" not in key assert "custom" in key assert "test" in key
def test_cache_created_key_includes_default_version(): cache = Cache("dummy://null", version="beta") key = cache.make_key("test") assert "beta" in key assert "test" in key
def test_cache_created_key_includes_prefix(): cache = Cache("dummy://null", key_prefix="prod") key = cache.make_key("test") assert key.startswith("prod") assert "test" in key