laureano arcanio wrote:
> Hy guys, I'm building a model for my os project and i want to make it
> importable to an existing TG2 app. So far I've created this model in
> python package, and I'm not sure how to define The medatata and
> Session to pick the one defined in a tg2 app. To be able of just
> import this model in the app model directory..
You don't need tg2's metadata, just the session, something like this:

# some_model.py
from sqlalchemy.orm import mapper # Use this mapper, not the one
associated to a scoped session
from sqlalchemy import ....

metadata = MetaData() # don't bind it to an engine either

foo = Table('foo', metadata, ...)

class Foo(object): pass

mapper(Foo, foo)

# then in tg2, when the config has been loaded

engine = engine_from_config(config)
Session = scopedsession(sessionmaker(bind=engine))

This session knows what database to talk to, you now use your models as
usual (forget about the query attribute since the mapper you're using is
not bound to any session automatically)

@expose(..)
def show_all_foos(self):
    foos = DBSession.query(Foo).all()
    ....

Not having a query attribute in every model is not that bad, you just
have to do things a little bit differently, example:

class Foo(object):
    def  do_something_with_bar(self, bar):
        session = sqlalchemy.orm.object_session(self) # if this Foo
instance was returned by a query from TG's DBSession, object_session
will return that session object
        similar_bars = session.query(bar.__class__).filter(bar.foo ==
foo).all()
        ...

A class method is a little bit trickier since you can't get a ref. to
the session, you'll have to pass it as a parameter:

class Foo(object):
    @classmethod
    def all_broken_foos(cls, session):
        return session.query(cls).filter(cls.broken==True)

Ahh, you also need to save your objects explicitly in the session since
they're not saved automatically by the scoped session's mapper.

Alternatively you can also define the scoped session in your model's
package, use the contextual mapper (to have the query attr. etc...), and
then use this session from tg2 instead of the one tg2 provides. You'll
need to take care of properly committing it, removing it after the
request is done, etc...

Alberto



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"TurboGears Trunk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/turbogears-trunk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to