satool.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import cherrypy
  2. __all__ = ['SATool']
  3. class SATool(cherrypy.Tool):
  4. def __init__(self):
  5. """
  6. The SA tool is responsible for associating a SA session
  7. to the SA engine and attaching it to the current request.
  8. Since we are running in a multithreaded application,
  9. we use the scoped_session that will create a session
  10. on a per thread basis so that you don't worry about
  11. concurrency on the session object itself.
  12. This tools binds a session to the engine each time
  13. a requests starts and commits/rollbacks whenever
  14. the request terminates.
  15. """
  16. cherrypy.Tool.__init__(self, 'on_start_resource',
  17. self.bind_session,
  18. priority=20)
  19. def _setup(self):
  20. cherrypy.Tool._setup(self)
  21. cherrypy.request.hooks.attach('on_end_resource',
  22. self.commit_transaction,
  23. priority=80)
  24. def bind_session(self):
  25. """
  26. Attaches a session to the request's scope by requesting
  27. the SA plugin to bind a session to the SA engine.
  28. """
  29. session = cherrypy.engine.publish('bind-session').pop()
  30. cherrypy.request.db = session
  31. def commit_transaction(self):
  32. """
  33. Commits the current transaction or rolls back
  34. if an error occurs. Removes the session handle
  35. from the request's scope.
  36. """
  37. if not hasattr(cherrypy.request, 'db'):
  38. return
  39. cherrypy.request.db = None
  40. cherrypy.engine.publish('commit-session')