Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6625039
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T21:43:33+00:00 2026-05-25T21:43:33+00:00

In my SQLAlchemy app I have the following model: from sqlalchemy import Column, String

  • 0

In my SQLAlchemy app 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()):
    # ...
    label = Column(String(20), unique=True)

    def save(self, force=False):
        DBSession.add(self)
        if force:
            DBSession.flush()

Later in code for every new MyModel objects I want to generate label randomly, and just regenerate it if the generated value is already exist in DB.
I’m 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 in case when first generated label is not unique and save() called on the second (or later) iteration:

 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 url_label is not unique... 

When I add DBSession.rollback() in the position (*) I get this:

 ResourceClosedError: The transaction is closed

What should I do to handle this situation correctly?
Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T21:43:33+00:00Added an answer on May 25, 2026 at 9:43 pm

    If your session object rolls back essentially you have to create a new session and refresh your models before you can start again. And if you are use zope.sqlalchemy you should be using transaction.commit() and transaction.abort() to control things. So your loop would look something like this:

    # you'll also need this import after your zope.sqlalchemy import statement
    import transaction
    
    while True:
        my_model.label = generate_label()
        try:
            transaction.commit()
        except IntegrityError:
            # need to use zope.sqlalchemy to clean things up
            transaction.abort()
            # recreate the session and re-add your object
            session = DBSession()
            session.add(my_model)
        else:
            break
    

    I’ve pulled the use of the session object out of the object’s save method here. I am not entirely sure how the ScopedSession refreshes itself when being used at the class level as you have done. Personally, I think embedding SqlAlchemy stuff inside your models doesn’t really work well with SqlAlchemy’s unit of work approach to things any how.

    If your label object really is a generated and unique value, then I would agree with TokenMacGuy and just use a uuid value.

    Hope that helps.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

The SQLAlchemy ORM tutorial uses this class: >>> from sqlalchemy import Column, Integer, String
To provide an activity log in my SQLAlchemy-based app, I have a model like
I have a Pylons app that I'm using SqlAlchemy declarative models for. In order
I'm using the SQLAlchemy Python ORM in a Pylons project. I have a class
I have an SQLAlchemy ORM class, linked to MySQL, which works great at saving
I have model class CreatedMixin(object): __abstract__ = True @declared_attr def created_by(cls): return Column(Integer, ForeignKey('user.user_id',
SqlAlchemy newbie question: Base = declarative_base() class A(Base): __tablename__ = 'as' id = Column(Integer,
I'm using CherryPy, Mako templates, and SQLAlchemy in a web app. I'm coming from
I am using SQlAlchemy in my web project. What should I use - scoped_session(sessionmaker())
I have installed virtualenv along with flask, werkzeug, jinja2 and SQLAlchemy. I was following

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.