Make session global in model
This commit is contained in:
parent
cbcfd4a5bf
commit
09d56d1c27
41
songdb.py
41
songdb.py
@ -24,8 +24,20 @@ pytiger.logging.config.basic_config(stderr=False, level=logging.INFO)
|
||||
log = logging.getLogger(__name__)
|
||||
log.info("Starting")
|
||||
|
||||
# Declare mapping
|
||||
# Create session at the global level as per
|
||||
# https://docs.sqlalchemy.org/en/13/orm/session_basics.html
|
||||
|
||||
# Set up database connection
|
||||
log.info("Connect to database")
|
||||
engine = sqlalchemy.create_engine(f"{MYSQL_CONNECT}?charset=utf8",
|
||||
encoding='utf-8',
|
||||
echo=DISPLAY_SQL)
|
||||
Base = declarative_base()
|
||||
Base.metadata.create_all(engine)
|
||||
|
||||
# Create a Session
|
||||
Session = sessionmaker(bind=engine)
|
||||
session = Session()
|
||||
|
||||
|
||||
# Database classes
|
||||
@ -47,7 +59,7 @@ class Tracks(Base):
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_or_create(cls, session, path):
|
||||
def get_or_create(cls, path):
|
||||
try:
|
||||
track = session.query(cls).filter(cls.path == path).one()
|
||||
except NoResultFound:
|
||||
@ -56,30 +68,16 @@ class Tracks(Base):
|
||||
session.add(track)
|
||||
return track
|
||||
|
||||
|
||||
@staticmethod
|
||||
def search_titles(text):
|
||||
return Tracks.query.filter(
|
||||
Tracks.title.ilike(text)
|
||||
return session.query(Tracks).filter(
|
||||
Tracks.title.ilike(f"%{text}%")
|
||||
).all()
|
||||
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
"Main loop"
|
||||
|
||||
# Set up database connection
|
||||
log.info("Connect to database")
|
||||
engine = sqlalchemy.create_engine(f"{MYSQL_CONNECT}?charset=utf8",
|
||||
encoding='utf-8',
|
||||
echo=DISPLAY_SQL)
|
||||
Base.metadata.create_all(engine)
|
||||
|
||||
# Create a Session
|
||||
Session = sessionmaker(bind=engine)
|
||||
session = Session()
|
||||
|
||||
# Parse command line
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument('-u', '--update',
|
||||
@ -90,12 +88,12 @@ def main():
|
||||
# Run as required
|
||||
if args.update:
|
||||
log.info("Updating database")
|
||||
update_db(session)
|
||||
update_db()
|
||||
|
||||
log.info("Finished")
|
||||
|
||||
|
||||
def update_db(session):
|
||||
def update_db():
|
||||
"""
|
||||
Repopulate database
|
||||
|
||||
@ -109,8 +107,7 @@ def update_db(session):
|
||||
path = os.path.join(root, f)
|
||||
ext = os.path.splitext(f)[1]
|
||||
if ext in [".flac", ".mp3"]:
|
||||
track = Tracks.get_or_create(session,
|
||||
os.path.relpath(path, ROOT))
|
||||
track = Tracks.get_or_create(os.path.relpath(path, ROOT))
|
||||
tag = TinyTag.get(path)
|
||||
track.title = tag.title
|
||||
track.artist = tag.artist
|
||||
|
||||
Loading…
Reference in New Issue
Block a user