73 lines
2.1 KiB
Python
73 lines
2.1 KiB
Python
import inspect
|
|
import os
|
|
import sqlalchemy
|
|
|
|
from config import Config
|
|
from contextlib import contextmanager
|
|
from log import DEBUG
|
|
from sqlalchemy.orm import (sessionmaker, scoped_session)
|
|
|
|
|
|
class Counter:
|
|
def __init__(self):
|
|
self.count = 0
|
|
|
|
def __repr__(self):
|
|
return(f"<Counter({self.count=})>")
|
|
|
|
def inc(self):
|
|
self.count += 1
|
|
return self.count
|
|
|
|
def dec(self):
|
|
self.count -= 1
|
|
return self.count
|
|
|
|
|
|
MM_ENV = os.environ.get('MM_ENV', 'PRODUCTION')
|
|
testing = False
|
|
|
|
if MM_ENV == 'PRODUCTION':
|
|
dbname = os.environ.get('MM_PRODUCTION_DBNAME', 'musicmuster_prod')
|
|
dbuser = os.environ.get('MM_PRODUCTION_DBUSER', 'musicmuster')
|
|
dbpw = os.environ.get('MM_PRODUCTION_DBPW', 'xxxmusicmuster')
|
|
dbhost = os.environ.get('MM_PRODUCTION_DBHOST', 'localhost')
|
|
elif MM_ENV == 'TESTING':
|
|
dbname = os.environ.get('MM_TESTING_DBNAME', 'musicmuster_testing')
|
|
dbuser = os.environ.get('MM_TESTING_DBUSER', 'musicmuster_testing')
|
|
dbpw = os.environ.get('MM_TESTING_DBPW', 'musicmuster_testing')
|
|
dbhost = os.environ.get('MM_TESTING_DBHOST', 'localhost')
|
|
testing = True
|
|
elif MM_ENV == 'DEVELOPMENT':
|
|
dbname = os.environ.get('MM_DEVELOPMENT_DBNAME', 'musicmuster_dev')
|
|
dbuser = os.environ.get('MM_DEVELOPMENT_DBUSER', 'musicmuster')
|
|
dbpw = os.environ.get('MM_DEVELOPMENT_DBPW', 'musicmuster')
|
|
dbhost = os.environ.get('MM_DEVELOPMENT_DBHOST', 'localhost')
|
|
else:
|
|
raise ValueError(f"Unknown MusicMuster environment: {MM_ENV=}")
|
|
|
|
MYSQL_CONNECT = f"mysql+mysqldb://{dbuser}:{dbpw}@{dbhost}/{dbname}"
|
|
|
|
engine = sqlalchemy.create_engine(
|
|
MYSQL_CONNECT,
|
|
encoding='utf-8',
|
|
echo=Config.DISPLAY_SQL,
|
|
pool_pre_ping=True
|
|
)
|
|
|
|
|
|
# Session = scoped_session(sessionmaker(bind=engine))
|
|
@contextmanager
|
|
def Session():
|
|
frame = inspect.stack()[2]
|
|
file = frame.filename
|
|
function = frame.function
|
|
lineno = frame.lineno
|
|
Session = scoped_session(sessionmaker(bind=engine))
|
|
DEBUG(f"Session acquired, {file=}, {function=}, {lineno=}, {Session=}",
|
|
True)
|
|
yield Session
|
|
DEBUG(" Session released", True)
|
|
Session.commit()
|
|
Session.close()
|