blivechat/models/database.py

33 lines
864 B
Python
Raw Permalink Normal View History

2020-02-03 16:18:21 +08:00
# -*- coding: utf-8 -*-
from typing import *
import sqlalchemy.orm
import config
2023-07-29 01:07:04 +08:00
_engine: Optional[sqlalchemy.Engine] = None
class OrmBase(sqlalchemy.orm.DeclarativeBase):
pass
2020-02-03 16:18:21 +08:00
2024-02-18 17:04:20 +08:00
def init():
2020-02-03 16:18:21 +08:00
cfg = config.get_config()
2023-07-29 01:07:04 +08:00
global _engine
2023-07-31 23:29:02 +08:00
_engine = sqlalchemy.create_engine(
cfg.database_url,
pool_size=5, # 保持的连接数
max_overflow=5, # 临时的额外连接数
pool_timeout=3, # 连接数达到最大时获取新连接的超时时间
# pool_pre_ping=True, # 获取连接时先检测是否可用
pool_recycle=60 * 60, # 回收超过1小时的连接防止数据库服务器主动断开不活跃的连接
2024-02-18 17:04:20 +08:00
# echo=cfg.debug, # 输出SQL语句
2023-07-31 23:29:02 +08:00
)
2020-02-03 16:18:21 +08:00
2022-02-15 00:18:46 +08:00
OrmBase.metadata.create_all(_engine)
2020-02-03 16:18:21 +08:00
2023-07-29 01:07:04 +08:00
def get_session() -> sqlalchemy.orm.Session:
return sqlalchemy.orm.Session(_engine)