zhenxun_bot/services/db_context.py

29 lines
834 B
Python
Raw Normal View History

2021-12-01 14:03:34 +08:00
from gino import Gino
from .log import logger
2022-05-28 22:50:23 +08:00
from utils.text_utils import prompt2cn
2021-12-01 14:03:34 +08:00
from configs.config import bind, sql_name, user, password, address, port, database
# 全局数据库连接对象
db = Gino()
async def init():
2022-05-28 22:50:23 +08:00
if not bind and (not user and not password and not address and not port and not database):
raise ValueError("\n" + prompt2cn("数据库配置未填写", 28))
2021-12-01 14:03:34 +08:00
i_bind = bind
if not i_bind:
i_bind = f"{sql_name}://{user}:{password}@{address}:{port}/{database}"
try:
await db.set_bind(i_bind)
await db.gino.create_all()
logger.info(f'Database loaded successfully!')
except Exception as e:
2022-01-05 22:32:59 +08:00
raise Exception(f'数据库连接错误.... {type(e)}: {e}')
2021-12-01 14:03:34 +08:00
async def disconnect():
await db.pop_bind().close()