saplugin.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import cherrypy
  2. from cherrypy.process import wspbus, plugins
  3. from sqlalchemy import create_engine
  4. from sqlalchemy.orm import scoped_session, sessionmaker
  5. __all__ = ['SAEnginePlugin']
  6. class SAEnginePlugin(plugins.SimplePlugin):
  7. def __init__(self, bus, connection_string=None):
  8. """
  9. The plugin is registered to the CherryPy engine and therefore
  10. is part of the bus (the engine *is* a bus) registery.
  11. We use this plugin to create the SA engine. At the same time,
  12. when the plugin starts we create the tables into the database
  13. using the mapped class of the global metadata.
  14. """
  15. plugins.SimplePlugin.__init__(self, bus)
  16. self.sa_engine = None
  17. self.connection_string = connection_string
  18. self.session = scoped_session(sessionmaker(autoflush=True,
  19. autocommit=False))
  20. def start(self):
  21. self.bus.log('Starting up DB access')
  22. self.sa_engine = create_engine(self.connection_string, echo=False)
  23. self.bus.subscribe("bind-session", self.bind)
  24. self.bus.subscribe("commit-session", self.commit)
  25. def stop(self):
  26. self.bus.log('Stopping down DB access')
  27. self.bus.unsubscribe("bind-session", self.bind)
  28. self.bus.unsubscribe("commit-session", self.commit)
  29. if self.sa_engine:
  30. self.sa_engine.dispose()
  31. self.sa_engine = None
  32. def bind(self):
  33. """
  34. Whenever this plugin receives the 'bind-session' command, it applies
  35. this method and to bind the current session to the engine.
  36. It then returns the session to the caller.
  37. """
  38. self.session.configure(bind=self.sa_engine)
  39. return self.session
  40. def commit(self):
  41. """
  42. Commits the current transaction or rollbacks if an error occurs.
  43. In all cases, the current session is unbound and therefore
  44. not usable any longer.
  45. """
  46. try:
  47. self.session.commit()
  48. except:
  49. self.session.rollback()
  50. raise
  51. finally:
  52. self.session.remove()