title: What's the recommended scoped_session usage pattern in a multithreaded sqlalchemy webapp?
body: <p>I'm writing an application with python and sqlalchemy-0.7. It starts by initializing the sqlalchemy orm (using declarative) and then it starts a multithreaded web server - I'm currently using web.py for rapid prototyping but that could change in the future. I will also add other "threads" for scheduled jobs and so on, probably using other python threads.</p>
  
  <p>From SA documentation I understand I have to use scoped_session() to get a thread-local session, so my web.py app should end up looking something like:</p>
  
  <pre><code>import web
  from myapp.model import Session  # scoped_session(sessionmaker(bind=engine))
  from myapp.model import This, That, AndSoOn
  urls = blah...
  app  = web.application(urls, globals())
  
  class index:
      def GET(self):
          s = Session()
          # get stuff done
          Session().remove()
          return(stuff)
  
  class foo:
      def GET(self):
          s = Session()
          # get stuff done
          Session().remove()
          return(stuff)
  </code></pre>
  
  <p>Is that the Right Way to handle the session?</p>
  
  <p>As far as I understand, I should get a scoped_session at every method since it'll give me a thread local session that I could not obtain beforehand (like at the module level).</p>
  
  <p>Also, I should call .remove() or .commit() or <a href="http://www.sqlalchemy.org/docs/07/orm/session.html?highlight=scoped_session#lifespan-of-a-contextual-session" rel="noreferrer">something like them</a> at every method end, otherwise the session will still contain <a href="http://www.sqlalchemy.org/docs/07/orm/session.html#quickie-intro-to-object-states" rel="noreferrer">Persistent</a> objects and I would not be able to query/access the same objects in other threads?</p>
  
  <p>If that pattern is the correct one, it could probably be made better by writing it only once, maybe using a decorator? Such a decorator could get the session, invoke the method and then make sure to dispose the session properly. How would that pass the session to the decorated function?</p>