Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask + SQLAlchemy [ Determine Success of Commit ]

I have a view in flask that I want to use to display success when an object from a POST request is successfully committed.

In the controller, I have

us = User(data_that_is_not_valid)
db_session.add(us)
db_session.commit()

As of now, db_commit() throws an exception when the object can't be committed. Is there a more friendly way that just returns true or false to specify whether the object has been added to the database without throwing an error?

EDIT: Added copy of exception

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.8.0-py2.7-linux-x86_64.egg/sqlalchemy/orm/scoping.py", line 149, in do
    return getattr(self.registry(), name)(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.8.0-py2.7-linux-x86_64.egg/sqlalchemy/orm/session.py", line 719, in commit
    self.transaction.commit()
  File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.8.0-py2.7-linux-x86_64.egg/sqlalchemy/orm/session.py", line 350, in commit
    self._assert_active(prepared_ok=True)
  File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.8.0-py2.7-linux-x86_64.egg/sqlalchemy/orm/session.py", line 192, in _assert_active
    % self._rollback_exception
sqlalchemy.exc.InvalidRequestError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (IntegrityError) column email is not unique u'INSERT INTO users (name, email, password) VALUES (?, ?, ?)' ('test', '[email protected]', 'test')
like image 933
user1431282 Avatar asked May 02 '13 06:05

user1431282


People also ask

Does commit close the session SQLAlchemy?

commit() will then COMMIT the actual database transaction or transactions, if any, that are in place. Finally, all objects within the Session are expired as the transaction is closed out.

What does SQLAlchemy commit do?

Nested Transaction begin_nested() methods, the transaction object returned must be used to commit or rollback the SAVEPOINT. Calling the Session. commit() or Connection. commit() methods will always commit the outermost transaction; this is a SQLAlchemy 2.0 specific behavior that is reversed from the 1.

Does flush commit transaction SQLAlchemy?

The flush process always occurs within a transaction, even if the Session has been configured with autocommit=True , a setting that disables the session's persistent transactional state. If no transaction is present, Session. flush() creates its own transaction and commits it.

What is _sa_instance_state in SQLAlchemy?

_sa_instance_state is a non-database-persisted value used by SQLAlchemy internally (it refers to the InstanceState for the instance. While not directly relevant to this section, if we want to get at it, we should use the inspect() function to access it).


1 Answers

Your data should be prepared anyway. But this case is not data format case
And exception is always good, you just need to catch and use them

You should consider exception as returned False, also you should log the reason for fail for later solving of problem

failed=False
try:
   db_session.commit()
except Exception as e:
   #log your exception in the way you want -> log to file, log as error with default logging, send by email. It's upon you
   db_session.rollback()
   db_session.flush() # for resetting non-commited .add()
   failed=True
#some use of failed var, specific for your case if you need it

For better understanding of exceptions: Exceptions python docs
As for your specific exception looks like autocommit is your issue. Or not commited some previous SQL operation: Sqlalchemy docs

like image 92
Tigra Avatar answered Jan 01 '23 19:01

Tigra