mirror of
https://github.com/fastapi-practices/fastapi_best_architecture.git
synced 2025-08-15 03:15:10 +08:00

* feat: add postgresql db supports * change: change mysql conn str create way * fix: Modify the default alembic migration file to meet multi-database support * Update settings and lint * update models * Simplify database config * Simplify the get db method * Update create db url * Updated model type adaptation * Update sql scripts * Fix models type * Adaptation to postgresql code generation * Update README.md * Fix alembic file template * Update docker scripts
65 lines
1.7 KiB
Python
65 lines
1.7 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
import sys
|
|
|
|
from redis.asyncio import Redis
|
|
from redis.exceptions import AuthenticationError, TimeoutError
|
|
|
|
from backend.common.log import log
|
|
from backend.core.conf import settings
|
|
|
|
|
|
class RedisCli(Redis):
|
|
def __init__(self):
|
|
super(RedisCli, self).__init__(
|
|
host=settings.REDIS_HOST,
|
|
port=settings.REDIS_PORT,
|
|
password=settings.REDIS_PASSWORD,
|
|
db=settings.REDIS_DATABASE,
|
|
socket_timeout=settings.REDIS_TIMEOUT,
|
|
decode_responses=True, # 转码 utf-8
|
|
)
|
|
|
|
async def open(self):
|
|
"""
|
|
触发初始化连接
|
|
|
|
:return:
|
|
"""
|
|
try:
|
|
await self.ping()
|
|
except TimeoutError:
|
|
log.error('❌ 数据库 redis 连接超时')
|
|
sys.exit()
|
|
except AuthenticationError:
|
|
log.error('❌ 数据库 redis 连接认证失败')
|
|
sys.exit()
|
|
except Exception as e:
|
|
log.error('❌ 数据库 redis 连接异常 {}', e)
|
|
sys.exit()
|
|
|
|
async def delete_prefix(self, prefix: str, exclude: str | list = None):
|
|
"""
|
|
删除指定前缀的所有key
|
|
|
|
:param prefix:
|
|
:param exclude:
|
|
:return:
|
|
"""
|
|
keys = []
|
|
async for key in self.scan_iter(match=f'{prefix}*'):
|
|
if isinstance(exclude, str):
|
|
if key != exclude:
|
|
keys.append(key)
|
|
elif isinstance(exclude, list):
|
|
if key not in exclude:
|
|
keys.append(key)
|
|
else:
|
|
keys.append(key)
|
|
if keys:
|
|
await self.delete(*keys)
|
|
|
|
|
|
# 创建 redis 客户端单例
|
|
redis_client: RedisCli = RedisCli()
|