I am coming from the Zope world and implemented a SA integration layer z3c.sqlalchemy. It basically provides a 'wrapper' exposing a thread-local session as property and as a registry for mappers that can be accessed through a getMapper(mapper_name) method. Now with the declarative layer I am trying to get rid of the approach and basically define the mapper classes
on the module level and importing them from the other modules as needed.

The problem with module-level initialization is that you have little control
about 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

Attachment: pgp8Sn4MBKtP9.pgp
Description: PGP signature

Reply via email to