[Python] Sessions error: object already attached to session

Discussão em 'Python' iniciado por Stack, Maio 22, 2025.

  1. Stack

    Stack Membro Participativo

    Background: Flask / Flask-SQLAlchemy / Flask-WTF, using declarative and scoped session

    Simple POST operation:

    @tas.route('/order_add', methods=['GET', 'POST'])
    def tas_order_add():
    if request.method == 'POST':
    order_form = OrderForm()
    if order_form.validate_on_submit():
    order = Order()
    order_form.populate_obj(order)
    db_session.add(order)
    db_session.commit()


    Now trying to run it I get an error:


    InvalidRequestError: Object '' is already attached to session '1' (this is '2')
    ​

    Changing add to merge solves the problem, but:

    • I don't know why do I have to merge an object while I just initiated it

    • If I do change add to merge and try to define one of the properties something in line

      order = Order()
      order_form.populate_obj(order)
      order.order_status = OrderStatus.query.filter(OrderStatus.code=='PLACED').first()
      db_session.merge(order)
      db_session.commit()


      I get the same error, just now on OrderStatus object


      InvalidRequestError: Object '' is already attached to session '2' (this is '1')
      ​

    Can someone point me where I'm doing something wrong because it's driving me nuts. I do have some experience with SQLAlchemy but it's the first time I see such a behaviour and I can't pinpoint the problem.

    Searching all I found was a problem with double database session initialization but I don't belive it's this case.

    EDIT

    db_session is defined in separate file database.py with following content

    from sqlalchemy.engine import create_engine
    from sqlalchemy.ext.declarative.api import declarative_base
    from sqlalchemy.orm.scoping import scoped_session
    from sqlalchemy.orm.session import sessionmaker

    engine = create_engine('sqlite:///fundmanager_devel.db', convert_unicode=True)
    db_session = scoped_session(sessionmaker(autocommit=False,
    autoflush=False,
    bind=engine))
    Base = declarative_base()
    Base.query = db_session.query_property()

    Continue reading...

Compartilhe esta Página