In my SQLAlchemy application, I have the following model:
from sqlalchemy import Column, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker from zope.sqlalchemy import ZopeTransactionExtension DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) class MyModel(declarative_base()):
Later in the code for each new MyModel object I want to randomly generate a label and simply restore it if the generated value already exists in the database.
I am trying to do the following:
# my_model is an object of MyModel while True: my_model.label = generate_label() try: my_model.save(force=True) except IntegrityError: # label is not unique - will do one more iteration # (*) pass else: # my_model saved successfully - exit the loop break
but get this error if the first generated label not unique, and save() is called at the second (or later) iteration:
InvalidRequestError: This Session 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 url_label is not unique...
When I add DBSession.rollback() to position (*), I get the following:
ResourceClosedError: The transaction is closed
What should I do to cope with this situation correctly? Thanks
Dmitry A. Shashkin
source share