From 560c44141092d552de26964415da09d36cfbdeb6 Mon Sep 17 00:00:00 2001 From: Grant Makyan Date: Tue, 28 Apr 2026 23:48:37 +0300 Subject: [PATCH] Add optional Redis username and password support --- .env.example | 2 ++ app/__main__.py | 6 +----- app/config.py | 28 +++++++++++++++++++++++++++- 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/.env.example b/.env.example index 1a2b918..7b21f3c 100644 --- a/.env.example +++ b/.env.example @@ -6,3 +6,5 @@ BOT_EMOJI_ID=5417915203100613993 REDIS_HOST=redis REDIS_PORT=6379 REDIS_DB=0 +REDIS_USERNAME= +REDIS_PASSWORD= diff --git a/app/__main__.py b/app/__main__.py index a08c8c2..8181c97 100644 --- a/app/__main__.py +++ b/app/__main__.py @@ -63,11 +63,7 @@ async def main() -> None: config = load_config() # Initialize apscheduler - job_store = RedisJobStore( - host=config.redis.HOST, - port=config.redis.PORT, - db=config.redis.DB, - ) + job_store = RedisJobStore(**config.redis.connection_dict) apscheduler = AsyncIOScheduler( jobstores={"default": job_store}, ) diff --git a/app/config.py b/app/config.py index fe3be9f..4f0c084 100644 --- a/app/config.py +++ b/app/config.py @@ -33,6 +33,8 @@ class RedisConfig: HOST: str PORT: int DB: int + USERNAME: str | None + PASSWORD: str | None def dsn(self) -> str: """ @@ -40,7 +42,29 @@ def dsn(self) -> str: :return: The generated DSN. """ - return f"redis://{self.HOST}:{self.PORT}/{self.DB}" + if self.PASSWORD: + return f"redis://{self.USERNAME or ''}:{self.PASSWORD}@{self.HOST}:{self.PORT}/{self.DB}" + else: + return f"redis://{self.HOST}:{self.PORT}/{self.DB}" + + @property + def connection_dict(self) -> dict[str, str | int]: + """ + Connection kwargs for Redis clients. + """ + + args = dict( + host=self.HOST, + port=self.PORT, + db=self.DB, + ) + + if self.USERNAME: + args["username"] = self.USERNAME + if self.PASSWORD: + args["password"] = self.PASSWORD + + return args @dataclass @@ -76,5 +100,7 @@ def load_config() -> Config: HOST=env.str("REDIS_HOST"), PORT=env.int("REDIS_PORT"), DB=env.int("REDIS_DB"), + USERNAME=env.str("REDIS_USERNAME", None), + PASSWORD=env.str("REDIS_PASSWORD", None), ), )