I’m working on a Python server application using SQLAlchemy for database access. I would like to have engine, session and metadata objects in a meta.py module that are used throughout the program to access the database (like the Pylons convention).
The engine and session objects are initialized as None in the meta.py module, and then actually assigned real values in other modules. E.g.
model/meta.py:
engine = None
Session = None
metadata = Metadata()
model/__init__.py:
from simplesite.model import meta
def init_model():
# ...
sm = orm.sessionmaker(...)
meta.Session = orm.scoped_session(sm)
The trouble is when I import and run init_model() in another module, then import Session from meta.py, it is still set to None. I.e.
from model.meta import Session
from model import init_model
init_model()
# Session is still None!
Could someone please tell me why this is and/or how how it works in Pylons applications? I’m guessing the answer would be something more fundamental about how Python works?
Alternative suggestions on how to have a single point of database access throughout an application would also be appreciated (i.e. best practices for using SQLAlchemy in large applications).
I’m answering this since it looks like it’s just sitting here, although an answer was given in the comments by @katrielalex.
When you do
from model.meta import Session, you create a new local variable calledSessionthat is bound to the object from that module. Wheninit_model()runs, it rebinds the name inside themetamodule, but this doesn’t affect your local variable.You can achieve your desired effect by not accessing
meta.Sessionuntil afterinit_model()has done its work: