cache.py 1.02 KB
# cache_patch.py
import hashlib
from datetime import datetime

from starlette_caches.utils import cache as scache
from aiocache import Cache


REDIS_CONN = open('./docs/redis').read().strip()
REDIS_CONN = REDIS_CONN.split(':')
# cache = Cache(
#     Cache.REDIS,
#     endpoint=REDIS_CONN[0], port=REDIS_CONN[1],
#     namespace="httpcache"
# )
cache = Cache()


def patched_generate_cache_key(url, method, headers, varying_headers, cache):
    assert method in scache.CACHABLE_METHODS

    # vary_ctx = hashlib.md5(usedforsecurity=False)
    # for header in varying_headers:
    #     value = headers.get(header)
    #     if value is not None:
    #         vary_ctx.update(value.encode())
    #
    # vary_hash = vary_ctx.hexdigest()
    url_hash = hashlib.md5(
        str(url).encode("ascii"), usedforsecurity=False
    ).hexdigest()

    now = datetime.now()
    dataset_version = now.strftime('%Y%m%d')

    return f"cache_presupuestov1.{dataset_version}.{method}.{url_hash}"


scache.generate_cache_key = patched_generate_cache_key