blivechat/models/database.py

35 lines
826 B
Python
Raw Normal View History

2020-02-03 16:18:21 +08:00
# -*- coding: utf-8 -*-
import contextlib
from typing import *
import sqlalchemy.ext.declarative
import sqlalchemy.orm
import config
OrmBase = sqlalchemy.ext.declarative.declarative_base()
2022-02-15 00:18:46 +08:00
_engine = None
_DbSession: Optional[Type[sqlalchemy.orm.Session]] = None
2020-02-03 16:18:21 +08:00
2021-07-17 13:03:45 +08:00
def init(_debug):
2020-02-03 16:18:21 +08:00
cfg = config.get_config()
2022-02-15 00:18:46 +08:00
global _engine, _DbSession
# engine = sqlalchemy.create_engine(cfg.database_url, echo=debug)
2022-02-15 00:18:46 +08:00
_engine = sqlalchemy.create_engine(cfg.database_url)
_DbSession = sqlalchemy.orm.sessionmaker(bind=_engine)
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
@contextlib.contextmanager
2022-02-15 00:18:46 +08:00
def get_session() -> ContextManager[sqlalchemy.orm.Session]:
session = _DbSession()
2020-02-03 16:18:21 +08:00
try:
yield session
2021-07-17 13:03:45 +08:00
except BaseException:
2020-02-03 16:18:21 +08:00
session.rollback()
raise
finally:
session.close()