from contextlib import contextmanager from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///db.db', convert_unicode=True) session_factory = sessionmaker(autocommit=False, autoflush=False, bind=engine) @contextmanager def Session(): session = session_factory() try: yield session session.commit() except: session.rollback() raise finally: session.close() Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) username = Column(String, nullable=False, unique=True) passwordhash = Column(String, nullable=False) def init_db(): Base.metadata.create_all(bind=engine)