Files
fastapi_best_architecture/backend/database/db_redis.py
Wu Clan 5e438c685d Refactor the backend architecture (#299)
* define the basic architecture

* Update script and deployment file locations

* Update the route registration

* Fix CI download dependencies

* Updated ruff to 0.3.3

* Update app subdirectory naming

* Update the model import

* fix pre-commit pdm lock

* Update the service directory naming

* Add CRUD method documents

* Fix the issue of circular import

* Update the README document

* Update the SQL statement for create tables

* Update docker scripts and documentation

* Fix docker scripts

* Update the backend README.md

* Add the security folder and move the redis client

* Update the configuration item

* Fix environment configuration reads

* Update the default configuration

* Updated README description

* Updated the user registration API

* Fix test cases

* Update the celery configuration

* Update and fix celery configuration

* Updated the celery structure

* Update celery tasks and api

* Add celery flower

* Update the import style

* Update contributors
2024-03-22 18:16:15 +08:00

65 lines
1.7 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from redis.asyncio.client 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)
for key in keys:
await self.delete(key)
# 创建 redis 客户端实例
redis_client = RedisCli()