Реализация FastApi-кэша в проекте Django python с помощью docker
В настоящее время пытаюсь кэшировать некоторые дорогие запросы к базе данных в проекте Django.
Это код в том виде, в котором он сейчас существует, у меня проблемы с проверкой того, что происходит не так. В настоящее время получаю ошибку, которая гласит
redis.exceptions.ConnectionError: Error -2 connecting to redis:6379. -2.
После некоторых поисков выяснилось, что мне не хватает 'redis-сервера', но после добавления его в requirements.py я столкнулся с этой ошибкой:
ERROR: No matching distribution found for redis-server==5.0.7
Я также пробовал другую версию, которую я вижу в списке, 6.0rc2, без успеха
Ниже приведен полный код, который я пытаюсь запустить:
import logging
from django.core.exceptions import ObjectDoesNotExist
from fastapi import Depends, FastAPI
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
from fastapi_cache.decorator import cache
from redis import asyncio as aioredis
LOGGER = get_logger_with_context(logging.getLogger(__name__))
@app.on_event("startup")
async def on_startup() -> None:
redis = aioredis.from_url("redis://redis", encoding="utf8", decode_responses=True, db=1)
FastAPICache.init(RedisBackend(redis), prefix="api-cache")
LOGGER.info("API has started.")
@app.on_event("shutdown")
async def on_shutdown() -> None:
LOGGER.info("API has shutdown.")
@app.get("/health", include_in_schema=False)
def healthcheck() -> dict:
"""Lightweight healthcheck."""
return {"status": "OK"}
@router.get(
"/companies/attributes",
summary="Retrieve company attributes, including leadership attributes, perks and benefits, and industry",
response_model=CompanyAttributesOut,
status_code=200,
)
@cache(expire=60, coder=JsonCoder)
def get_company_attributes() -> CompanyAttributesOut:
"""Retrieve the company attributes."""
with async_safe():
return CompanyAttributesOut.from_database_model()