title: Sqlalchemy: Using decorator to provide thread-safe session for multiple functions
body: <p>I am working on something similar like <a href="https://stackoverflow.com/questions/5544774/">here</a> (multithreaded app with sqlalchemy), so I understood, that I should create a new session for each db-query.</p>
  
  <p>I wonder, if using a decorator for each method, which needs DB-access would make sense, or if there are traps using this approach. The decorator is constructed following <a href="http://docs.sqlalchemy.org/en/rel_0_9/orm/session_basics.html#when-do-i-construct-a-session-when-do-i-commit-it-and-when-do-i-close-it" rel="noreferrer">the last example here</a>.</p>
  
  <pre><code>def dbconnect(func):
      def inner(*args, **kwargs):
          session = Session()  # with all the requirements
          try:
              func(*args, session=session, **kwargs)
              session.commit()
          except:
              session.rollback()
              raise
          finally:
              session.close()
      return inner
  
  @dbconnect
  def some_function(some, arguments, session)
      session.query(...) # no commit, close, rollback required
  
  some_function("many", "different_arguments") 
  #session is not required, since provided by decorator
  </code></pre>
  
  <p>This would make it comparable easy to provide thread-safe DB-access to any function, without the need of implementing the whole try-except-finally-stuff redundant, but I am not sure, if this approach is fail-safe and pythonic, or if there exists another best-practice.</p>