Skip to content

Instantly share code, notes, and snippets.

@dmitric
Created March 24, 2012 18:06
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save dmitric/2185742 to your computer and use it in GitHub Desktop.
Save dmitric/2185742 to your computer and use it in GitHub Desktop.
SqlAlchemy usage with tornado backend
class Backend(object):
def __init__(self):
engine = create_engine("mysql://{0}:{1}@{2}/{3}".format(options.mysql_user, options.mysql_pass, options.mysql_host, options.mysql_db)
, pool_size = options.mysql_poolsize
, pool_recycle = 3600
, echo=options.debug
, echo_pool=options.debug)
self._session = sessionmaker(bind=engine)
@classmethod
def instance(cls):
"""Singleton like accessor to instantiate backend object"""
if not hasattr(cls,"_instance"):
cls._instance = cls()
return cls._instance
def get_session(self):
return self._session()
class BaseHandler(tornado.web.RequestHandler):
@property
def backend(self):
return Backend.instance()
class ExampleHandler(BaseHandler):
def get(self):
session = self.backend.get_session()
try:
"""Everything I need to do here"""
session.commit()
except Exception as e:
session.rollback()
finally:
session.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment