title: FastApi Sqlalchemy how to manage transaction (session and multiple commits)
body: <p>I have a CRUD with insert and update functions with <code>commit</code> at the end of the each one as follows:</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>@staticmethod
  def insert(db: Session, item: Item) -&gt; None:
      db.add(item)
      db.commit()
     
     
  @staticmethod
  def update(db: Session, item: Item) -&gt; None:
      ...
      db.commit()</code></pre>
  </div>
  </div>
  </p>
  <p>I have an endpoint which receives a sqlalchemy session from a FastAPI dependency and needs to insert and update atomically (DB transaction).</p>
  <p>What's the best practice when working with transactions? I can't work with the CRUD since it does more than one <code>commit</code>.</p>
  <p>How should I handle the transactions? Where do you commit your session? in the CRUD? or only once in the FastAPI dependency function for each request?</p>