🎨 Add Optional Password for Redis

This commit is contained in:
Nahida 2023-01-05 15:36:10 +08:00 committed by GitHub
parent 7013a61f49
commit 869713542a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 8 additions and 6 deletions

View File

@ -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"

View File

@ -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()

View File

@ -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_"