title: How to handle multiple requests without SQLAlchemy crashing/raising exceptions?
body: <p><strong>Context</strong>: I'm working on a Flask app, running on CherryPy, DB handled using SQLAlchemy ORM.</p>
  
  <p><strong>Problem:</strong></p>
  
  <p>The app runs fine and does everything I want, however, if I have a page which fetches some data from DB and displays, and I press and hold "Ctrl + R" or "F5". That is, continuously refresh a page, making that many DB requests. First few goes fine, and then it breaks.
  The following errors are logged:</p>
  
  <pre><code>(OperationalError) (2013, 'Lost connection to MySQL server during query')
  
  Can't reconnect until invalid transaction is rolled back (original cause: 
  InvalidRequestError: Can't reconnect until invalid transaction is rolled back)
  
  This result object does not return rows. It has been closed automatically.
  
  (ProgrammingError) (2014, "Commands out of sync; you can't run this command now")
  </code></pre>
  
  <p>There's also another error which bothers me (but not logged this time), it's </p>
  
  <p><code>dictionary changed size during iteration</code></p>
  
  <p>This happens when I'm iterating through a query, using values obtained to populate a dictionary. The dictionary is local (scope of the dict) to the function. </p>
  
  <p><strong>More info:</strong></p>
  
  <p>How I am handling sessions:</p>
  
  <p>A new session is created when you enter any page, use that session to perform all the DB transactions, and the session is closed right before rendering the HTML. Technically, that means, the scope of session is the same as the HTTP request.</p>
  
  <p>I do a <code>session.rollback()</code> only when there's an exception raised during <code>updating</code> table or <code>inserting</code> into a table. No <code>rollback()</code> during any <code>query()</code> operations.
  I'm pretty sure I've made some silly mistakes or am not doing things the right way.</p>
  
  <p>Unlimited refreshes like that is not really a probably scenario, but can't be overlooked.
  Also, I think the behavior would be similar when there a lot of users using it at the same time.</p>
  
  <p><strong>How the SQLAlchemy engine, sessionmaker was handled</strong>:</p>
  
  <pre><code>sql_alchemy_engine = create_engine(self.db_string, echo=False, encoding="utf8", convert_unicode=True, pool_recycle=9)
  sqla_session = sessionmaker(bind=sql_alchemy_engine)
  </code></pre>
  
  <p>It's done only ONCE like it's recommended in the SQLA documentation, and a new session is created and returned <code>sqla_session()</code> whenever required.</p>