db.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. from contextlib import contextmanager
  2. from sqlalchemy import create_engine
  3. from sqlalchemy.ext.declarative import declarative_base
  4. from sqlalchemy.orm import Session
  5. from sqlalchemy.orm import sessionmaker
  6. from sqlalchemy.orm.scoping import scoped_session
  7. from core import constants
  8. engine = create_engine(
  9. f'sqlite:///{constants.DB_PATH}',
  10. connect_args={'check_same_thread': False},
  11. echo=constants.SQL_ALCHEMY_VERBOSE)
  12. Base = declarative_base()
  13. # session_factory = sessionmaker(autocommit=False, autoflush=False, bind=engine)
  14. # session = scoped_session(session_factory)
  15. # # session_ = Session()
  16. # #
  17. # #
  18. def session():
  19. return Session(engine)
  20. @contextmanager
  21. def session_scope():
  22. """Provide a transactional scope around a series of operations."""
  23. session = Session()
  24. try:
  25. yield session
  26. session.commit()
  27. except:
  28. session.rollback()
  29. raise
  30. finally:
  31. session.close()
  32. def create():
  33. if constants.DB_PATH.exists():
  34. raise FileExistsError('A db file already exists')
  35. Base.metadata.create_all(engine)
  36. def close():
  37. # session.remove()
  38. engine.dispose()