Background: Flask / Flask-SQLAlchemy / Flask-WTF using declarative and restricted 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 start it, I get an error message:
InvalidRequestError: Object '' is already attached to the session '1' (this is '2')
Changing add to merge solves the problem, but:
- I do not know why I need to combine the object while I initiated it.
If I change add to merge and try to define one of the properties of something on the 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, only now on the OrderStatus object
InvalidRequestError: Object '' is already attached to the session '2' (this is '1')
Can someone point me where I am doing something wrong, because it makes me go crazy. I have some experience with SQLAlchemy, but this is the first time I see this behavior and I canβt pinpoint the problem.
Finding everything I found was a problem with initializing a dual database session, but I do not believe this case.
EDIT
db_session is defined in a separate database.py file with the following contents
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()
source share