Thursday, March 05, 2009

using TurboGears 2 model outside TurboGears

Until/unless this ticket gets incorporated into the TurboGears 2 docs, I (for one) need a reminder about how I can make use of a sqlalchemy model, set up from a TurboGears 2 instance, for projects that don't actually start or use TurboGears. (I want a single, canonical sqlalchemy model for my database, for its web-based and non-web-based applications alike.)

Including this function in my model/__init__.py does the trick.

import paste.deploy, os.path
def externally_usable_session(configfile = 'development.ini'):
tg_home_directory = '/path/to/tg2instancehomedirectory'
conf_dict = paste.deploy.appconfig('config:%s' % os.path.join(tg_home_directory, configfile))
engine = create_engine(conf_dict['sqlalchemy.url'])
init_model(engine)
return DBSession()

1 comment:

Herbert L Roitblat, Ph.D said...

You also have to import sqlalchemy:
from sqlalchemy import *.

Then in your script, you can get the session using:

dbSession = pmodel.externally_usable_session('development.ini')