(This is the 2017 answer to the 2011 question). As @Stefano Borini noted, the easiest way in Tornado 4 is to simply allow RequestHandler to implicitly pass the session around . Tornado will monitor the state of the handler instance when using the coroutine decorator templates:
import logging _logger = logging.getLogger(__name__) from sqlalchemy import create_engine, exc as sqla_exc from sqlalchemy.orm import sessionmaker, exc as orm_exc from tornado import gen from tornado.web import RequestHandler from my_models import SQLA_Class Session = sessionmaker(bind=create_engine(...)) class BaseHandler(RequestHandler): @gen.coroutine def prepare(): self.db_session = Session() def on_finish(): self.db_session.close() class MyHander(BaseHandler): @gen.coroutine def post(): SQLA_Object = self.db_session.query(SQLA_Class)... SQLA_Object.attribute = ... try: db_session.commit() except sqla_exc.SQLAlchemyError: _logger.exception("Couldn't commit") db_session.rollback()
If you really need to reference the SQL Alchemy session asynchronously inside declarative_base (which I would consider as an anti-template, since it confused the model with the application), Amit Matani has a non-working example here .
source share