I'm new to the concept of using a global variable to spawn new DB Sessions. I want to import settings.py
file into manage.py
to call method that loads environment variables using the .env
helper library dotenv
. However, since the variables are not yet initialized in the moment of settings.py
import into manage.py (the .env
filename is yet to be read from sys.argv
), the engine construction line cannot stay "in plain sight" (unindented). I wonder if settings.py
are the right place for such a global variable? I'm used to settings.py
only containing dictionaries of basic types, no objects or classes.
Right now init_db_globs
looks like this.
# set the default db .env file name
def init_db_globs(db_name='db', env_file_name='.env'):
# refer to global vars
global engine, session
# connection string template
template_uri = 'postgresql://{}:{}@{}:{}/{}'
# load env vars
load_dotenv(env_file_name)
# load database parameters from env vars
dbs = {
'db': {
# 'var': os.getenv('DB_VAR'),
},
'db_test': {
# 'var': os.getenv('DB_VAR_TEST'),
}
}
uri = template_uri.format(db['user'],db['password'],db['host'],db['port'],db['name'])
engine = create_engine(uri, params_list)
# create a configured "Session" class
Session = orm.sessionmaker(bind=engine)
# init global session
session = Session()
# create global vars
session = None
engine = None
How should this be improved?