code: def serialized(func):
      
  
      @wraps(func)
      def wrapper(*args, **kw):
          attempts = 100
          session.remove()
          while attempts > 0:
              try:
                  session.connection(
                      execution_options={"isolation_level": "SERIALIZABLE"}
                  )
                  result = func(*args, **kw)
                  session.commit()
                  return result
              except OperationalError as exc:
                  session.rollback()
                  if isinstance(exc.orig, TransactionRollbackError):
                      if attempts > 0:
                          attempts -= 1
                      else:
                          raise Exception(
                              "Could not commit serialized transaction "
                              "after 100 attempts."
                          )
                  else:
                      raise
              finally:
                  session.remove()
              time.sleep(random.expovariate(0.5))
  
      return wrapper
docs: Run a function within a db transaction using SERIALIZABLE isolation.
  
      With this isolation level, committing will fail if this transaction
      read data that was since modified by another transaction. So we need
      to handle that case and retry the transaction.