title: SQLAlchemy session: how to keep it alive?
body: <p>I have a session object that gets passed around a whole lot and at some point the following lines of code are called (this is unavoidable):</p>
  
  <pre><code>import transaction
  transaction.commit()
  </code></pre>
  
  <p>This renders the session unusable (by closing it I think).</p>
  
  <p>My question is two part:</p>
  
  <ol>
  <li>How do I check if a session is still alive and well?</li>
  <li>Is there a quick way to revitalize a dead session?</li>
  </ol>
  
  <p>For 2: The only way I currently know is to use sqlalchemy.orm.scoped_session, then call query(...)get(id) many times to recreate the necessary model instances but this seems pretty darn inefficient.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Here's an example of the sequence of events that causes the error:</p>
  
  <pre><code>modelInstance = DBSession.query(ModelClass).first()
  import transaction
  transaction.commit()
  modelInstance.some_relationship
  </code></pre>
  
  <p>And here is the error:</p>
  
  <pre><code>sqlalchemy.orm.exc.DetachedInstanceError: Parent instance &lt;CategoryNode at 0x7fdc4c4b3110&gt; is not bound to a Session; lazy load operation of attribute 'children' cannot proceed
  </code></pre>
  
  <p>I don't really want to turn off lazy loading.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>DBSession.is_active seems to be no indication of whether or not the session is in fact alive and well in this case:</p>
  
  <pre><code>transaction.commit()
  print(DBSession.is_active)
  </code></pre>
  
  <p>this prints True...</p>
  
  <p><strong>EDIT</strong>
  This seemed too big for a comment so I'm putting it here.</p>
  
  <p>zzzeek said:
  "An expired object will automatically load new state from the database, via the Session, as soon as you access anything on it, so there's no need to tell the Session to do anything here."</p>
  
  <p>So how do I get stuff committed in such a way that this will happen? calling transaction.commit is wrong, what's the correct way?</p>