s3rius / FastAPI-template

Feature rich robust FastAPI template.
MIT License
1.79k stars 161 forks source link

Is it the best way to put redis, kafka and other services in the app.state? #180

Closed lpdswing closed 11 months ago

s3rius commented 11 months ago

Hello. Which one? Like the one that exists now in template?

lpdswing commented 11 months ago

Hello. Which one? Like the one that exists now in template?

yes,I want to know whether it is the one that exists now in template better than put the redis and other components in the global, Is it better to put them in dpends?

def get_db() -> Generator:
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()

async def get_redis():
    url = f"redis://{settings.REDIS_HOST}"
    r = redis.from_url(
        url,
        port=settings.REDIS_PORT,
        password=settings.REDIS_PASSWORD,
        db=settings.REDIS_DB,
        encoding="utf-8",
        decode_responses=True,
    )
    return r

async def dependency_redis() -> AsyncIterator[redis.Redis]:
    redis = await get_redis()
    try:
        yield redis
    finally:
        await redis.close(close_connection_pool=True)
s3rius commented 11 months ago

I think it's better, because it makes the project more flexible.

So, of course, you may prefer global variables. But it becomes hard to manage in big projects. I have had such experience before.

For small project it may be seem inappropriate, or overcomplicated. But since it works for both cases I decided to do it that way.

If you disagree with this, please provide the solutio you'd like to see.

lpdswing commented 11 months ago

I think it's better, because it makes the project more flexible.

So, of course, you may prefer global variables. But it becomes hard to manage in big projects. I have had such experience before.

For small project it may be seem inappropriate, or overcomplicated. But since it works for both cases I decided to do it that way.

If you disagree with this, please provide the solutio you'd like to see.

thanks very much, I get it