on the module level and importing them from the other modules as needed.
The problem with module-level initialization is that you have little controlabout initialization parameter (e.g. I must be able to pass the DSN as parameter). My current code looks a bit like this:
main.py:
--------
dsn = get_dsn_from_some_config_object(..)
import model
model.setup(dsn)
from model import MyMapper, Session
session = Session()
rows = session.query(MyMapper).filter_by(....).all()
model.py:
---------
def setup(dsn):
engine= create_engine(...)
session = scoped_session(sessionmaker(...)))
Base = declarative_base(engine)
class MyMapper(Base):
__table__ = Table('mytable', Base.metadata, autoload=True)
for k,v in locals().items():
globals()[k]=v
This approach is ugly (because of putting the mapper within the local
scope into the global scope (in order to make them importable) and because
of this code within main.py:
import model
model.setup(dsn)
from model import MyMapper, Session
This there any better pattern for implementing this?
Andreas
pgp8Sn4MBKtP9.pgp
Description: PGP signature
