title: What is the best way to manage sqlalchemy sessions in a flask app in the given project structure?
body: <p>Hi Sorry this is a very open ended question and more like a coding advice. Looking for what are the best practises for using sqlalchemy session for flask projects. Couldn't find a blog that could answer my question, hence asking it here.</p>
  
  <p>I have project structure for a flask app similar to following:</p>
  
  <pre><code>---services
       --- service_1.py
       --- service_2.py
  ---models.py
  ---adapter.py
  ---app.py
  </code></pre>
  
  <p>All the business logic resides in services. Methods in services call methods in adapter for any interaction with DB.</p>
  
  <p>Adapter is data access layer all the sql queries are happening inside it. Adaper code is like this:</p>
  
  <pre><code>from .models import *
  class DBAdapter(object):
      def __init__(self, session):
          self._db_session = get_session() # get a sql alchemy session
  
      def create_customer(**kwargs):
          c = Customer(**kwargs)
          self._db_session.add(c)
          return c
      .
      .
      .
      def commit(self):
          self.session.commit()
  
      def close_session(self):
          self.session.close()
  </code></pre>
  
  <p>The service looks something like this:</p>
  
  <pre><code>from ..adapter import DBAdapter
  
  class Service1(object):
      def __init__(self, a):
         self.a = a
         self._db_adapter = DBAdapter()
  
      def do_something(self, x, y):
         if x != 10:
             self.create_something(x)
             self._db_adapter.commit()
             self._db_adapter.close_session()
             return
  
         self._db_adapter.create_customer(y)
         self._db_adapter.create_something_else(x)
         self._db_adapter.commit()
         self._db_adapter.close_session()
         return
  </code></pre>
  
  <p>Now the problem is how to close the session without repetition of <code>self._db_adapter.close_session()</code> before each return statement. It needs to be closed at two places once before return inside if condition then at the end. </p>
  
  <p>Should I create my data access layer <code>DBAdapter</code> in a different way?</p>
  
  <p>I want to keep my session clean and create it only when a service is initialized, so I can't put it in g object in flask like this:</p>
  
  <p><a href="https://stackoverflow.com/questions/35664436/flask-and-sqlalchemy-handling-sessions">Flask and sqlalchemy: handling sessions</a></p>