blivechat/models/database.py

36 lines
776 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()
engine = None
DbSession: Optional[Type[sqlalchemy.orm.Session]] = None
2021-07-17 13:03:45 +08:00
def init(_debug):
2020-02-03 16:18:21 +08:00
cfg = config.get_config()
global engine, DbSession
# engine = sqlalchemy.create_engine(cfg.database_url, echo=debug)
engine = sqlalchemy.create_engine(cfg.database_url)
2020-02-03 16:18:21 +08:00
DbSession = sqlalchemy.orm.sessionmaker(bind=engine)
OrmBase.metadata.create_all(engine)
@contextlib.contextmanager
def get_session():
session = DbSession()
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()