Attach the MediaGoblinApp to the engine, and provide a way for models to access

This allows SQLAlchemy models to gain access to app-level configuration
without the need for global variables.

This commit sponsored by Peter Hogg.  Thank you, Peter!
This commit is contained in:
Christopher Allan Webber 2014-12-03 13:13:58 -06:00
parent 5e5ea4a3e9
commit 7c563e91bf
4 changed files with 18 additions and 7 deletions

View File

@ -108,9 +108,9 @@ class MediaGoblinApp(object):
# Set up the database
if DISABLE_GLOBALS:
self.db_manager = setup_database(self.app_config['run_migrations'])
self.db_manager = setup_database(self)
else:
self.db = setup_database(self.app_config['run_migrations'])
self.db = setup_database(self)
# Quit app if need to run dbupdate
## NOTE: This is currently commented out due to session errors..

View File

@ -30,6 +30,10 @@ class GMGTableBase(object):
def _session(self):
return inspect(self).session
@property
def _app(self):
return self._session.bind.app
if not DISABLE_GLOBALS:
query = Session.query_property()

View File

@ -158,9 +158,14 @@ def _sqlite_disable_fk_pragma_on_connect(dbapi_con, con_record):
dbapi_con.execute('pragma foreign_keys=off')
def setup_connection_and_db_from_config(app_config, migrations=False):
def setup_connection_and_db_from_config(app_config, migrations=False, app=None):
engine = create_engine(app_config['sql_engine'])
# @@: Maybe make a weak-ref so an engine can get garbage
# collected? Not that we expect to make a lot of MediaGoblinApp
# instances in a single process...
engine.app = app
# Enable foreign key checking for sqlite
if app_config['sql_engine'].startswith('sqlite://'):
if migrations:

View File

@ -60,14 +60,16 @@ def setup_global_and_app_config(config_path):
return global_config, app_config
def setup_database(run_migrations=False):
app_config = mg_globals.app_config
global_config = mg_globals.global_config
def setup_database(app):
app_config = app.app_config
global_config = app.global_config
run_migrations = app_config['run_migrations']
# Load all models for media types (plugins, ...)
load_models(app_config)
# Set up the database
db = setup_connection_and_db_from_config(app_config, run_migrations)
db = setup_connection_and_db_from_config(
app_config, run_migrations, app=app)
if run_migrations:
#Run the migrations to initialize/update the database.
from mediagoblin.gmg_commands.dbupdate import run_all_migrations