igorbenav / FastAPI-boilerplate

An extendable async API using FastAPI, Pydantic V2, SQLAlchemy 2.0, PostgreSQL and Redis.
MIT License
632 stars 76 forks source link

Redis client not found when created background tasks in Swagger #151

Open scottyeung opened 2 months ago

scottyeung commented 2 months ago

Describe the bug or question A clear and concise description of what the bug or question is.

To Reproduce Please provide a self-contained, minimal, and reproducible example of your use case

async def is_rate_limited(db: AsyncSession, user_id: int, path: str, limit: int, period: int) -> bool:
    if client is None:
        logger.error("Redis client is not initialized.")
        raise Exception("Redis client is not initialized.")

Description Redis client was recognised as none when I tried to create background tasks in Swagger and caught exception in is_rate_limited

Screenshots

Screenshot 2024-09-08 at 5 12 24 PM Screenshot 2024-09-08 at 5 12 36 PM Screenshot 2024-09-08 at 5 14 44 PM

Additional context Add any other context about the problem here.

igorbenav commented 2 months ago

How did you run it? Using docker compose?

scottyeung commented 2 months ago

How did you run it? Using docker compose?

Exactly, docker-compose. Did I miss anything?

studentNinja commented 2 months ago

Having the exact same issue. Redis name in .env = redis , App started by docker compose up -d When trying to post a new task , getting raise Exception("Redis client is not initialized.")=

yucelz commented 1 month ago

I think the issue is that all the Redis connections and the pool are tied to the cache in setup.py, which means that anyone who isn't using the cache can't get to them.

I came up with a temporary fix. It's not ideal, but it does the job. I moved everything, like the is_rate_limited function, into cache.py, and now it works just fine.