title: sqlalchemy mysql connections not closing on flask api
body: <p>I have an API I have written in flask. It uses sqlalchemy to deal with a MySQL database. I don't use flask-sqlalchemy, because I don't like how the module forces you into a certain pattern for declaring the model.</p>
  <p>I'm having a problem in which my database connections are not closing. The object representing the connection is going out of scope, so I assume it is being garbage collected. I also explicitly call close() on the session. Despite this, the connections stay open long after the API call has returned its response.</p>
  <p>sqlsession.py: Here is the wrapper I am using for the session.</p>
  <pre><code>class SqlSession:
      def __init__(self, conn=Constants.Sql):
          self.db = SqlSession.createEngine(conn)
  
          Session = sessionmaker(bind=self.db)
          self.session = Session()
      @staticmethod
      def createEngine(conn):
          return create_engine(conn.URI.format(user=conn.USER, password=conn.PASS, host=conn.HOST, port=conn.PORT, database=conn.DATABASE, poolclass=NullPool))
  
      def close(self):
          self.session.close()
  </code></pre>
  <p>flaskroutes.py: Here is an example of the flask app instantiating and using the wrapper object. Note that it instantiates it in the beginning within the scope of the api call, then closes the session at the end, and presumably is garbage collected after the response is returned.</p>
  <pre><code>def commands(self, deviceId):
      sqlSession = SqlSession(self.sessionType) &lt;---
  
      commandsQueued = getCommands()
      jsonCommands = []
      for command in commandsQueued:
       jsonCommand = command.returnJsonObject()
       jsonCommands.append(jsonCommand)
       sqlSession.session.delete(command)
      sqlSession.session.commit()
      resp = jsonify({'commands': jsonCommands})
      sqlSession.close() &lt;---  
      resp.status_code = 200
      return resp
  </code></pre>
  <p>I would expect the connections to be cleared as soon as the HTTP response is made, but instead, the connections end up with the &quot;SLEEP&quot; state (when viewed in the MySQL command line interface 'show processlist').</p>