Karlo Lozovina escreveu:
engine = engine_from_config(config, 'sqlalchemy.')
init_model(engine)
Silly me :). What I wanted to say, I have to add that piece of code to
every action of my controllers. That seems somehow redundant to me...
?

I use an WSGI fake-middleware, which fires init_model and then returns the next-app. Here' some code, below. There's not much point in yielding or splitting the work into two functions... This is meant for multiple connections, to be used like this in paster. If you don't need multiple engines, you can simplify greatly by using engine_from_config() instead of reinventing the wheel.

---8<---
[filter:database]
use = egg:OurCompany#sqlalchemy
trac = postgres://trac:[EMAIL PROTECTED]/trac
trac.models = company.dubiousapp.model company.reportingapp.model
shipping = mssql://user:[EMAIL PROTECTED]/company
shipping.schema = shipping
shipping.models = company.shipping.model
shipping.module = pymssql
---8<---

---8<---
def parse(config):
   engines = dict()
   for key, info in config.items():
       name = key.split('.')[0]
       engines.setdefault(name, dict(uri=None, args=dict()))
       if '.' in key:
           key = key.split('.', 1)[1:2][0]
           assert key, key
engines[name]['args'][key] = info
       else:
           engines[name]['uri'] = info
return engines


def walk(engines):
   for _, info in engines.items():
       assert 'args' in info, info
       assert 'uri' in info, info
models = info['args'].pop('models')
       schema = info['args'].pop('schema', None)
       module = info['args'].pop('module', None)
       if module:
           module = resolver.resolve(module)
           info['args']['module'] = module
engine = sa.create_engine(info['uri'], **info['args'])
       for model in models.split():
           model = resolver.resolve(model)
           yield engine, model, schema


def sqlalchemy_filter_app_factory(app, _, **config):
   for engine, model, schema in walk(parse(config)):
       model.__init__(engine, schema = schema)
   return app
---8<---

If anyone cares enough to rework this crap a bit and post it, I'd be delighted!

Attachment: signature.asc
Description: OpenPGP digital signature

Reply via email to