From 869713542a738b84b01b3ddf6865f4ed0734deec Mon Sep 17 00:00:00 2001 From: Nahida Date: Thu, 5 Jan 2023 15:36:10 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20Add=20Optional=20Password=20for?= =?UTF-8?q?=20Redis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 1 + core/base/redisdb.py | 10 +++++----- core/config.py | 3 ++- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/.env.example b/.env.example index a3f0807..4c3c2d9 100644 --- a/.env.example +++ b/.env.example @@ -12,6 +12,7 @@ DB_DATABASE=paimon REDIS_HOST=127.0.0.1 REDIS_PORT=6379 REDIS_DB=0 +REDIS_PASSWORD="" # 联系 https://t.me/BotFather 使用 /newbot 命令创建机器人并获取 token BOT_TOKEN="xxxxxxx" diff --git a/core/base/redisdb.py b/core/base/redisdb.py index 7fb4583..1c171b2 100644 --- a/core/base/redisdb.py +++ b/core/base/redisdb.py @@ -1,4 +1,5 @@ import asyncio +from typing import Optional, Union import fakeredis.aioredis from redis import asyncio as aioredis @@ -15,11 +16,12 @@ class RedisDB(Service): def from_config(cls, config: BotConfig) -> Self: return cls(**config.redis.dict()) - def __init__(self, host="127.0.0.1", port=6379, database=0, loop=None): - self.client = aioredis.Redis(host=host, port=port, db=database) + def __init__( + self, host: str = "127.0.0.1", port: int = 6379, database: Union[str, int] = 0, password: Optional[str] = None + ): + self.client = aioredis.Redis(host=host, port=port, db=database, password=password) self.ttl = 600 self.key_prefix = "paimon_bot" - self._loop = loop async def ping(self): if await self.client.ping(): @@ -33,8 +35,6 @@ class RedisDB(Service): await self.ping() async def start(self): # pylint: disable=W0221 - if self._loop is None: - self._loop = asyncio.get_running_loop() logger.info("正在尝试建立与 [red]Redis[/] 连接", extra={"markup": True}) try: await self.ping() diff --git a/core/config.py b/core/config.py index de838e3..8745449 100644 --- a/core/config.py +++ b/core/config.py @@ -48,7 +48,8 @@ class MySqlConfig(Settings): class RedisConfig(Settings): host: str = "127.0.0.1" port: int = 6379 - database: int = Field(env="redis_db") + database: int = Field(default=0, env="redis_db") + password: Optional[str] = None class Config(Settings.Config): env_prefix = "redis_"