Pyramid / SQL Alchemy DetachedInstanceError

I am trying to implement email confirmation using the Pyramid framework. Here is the code that confirms the user in the database and redirects them to the main page.

user = DbSession.query(User).filter_by(email=email).one() if user.approved: return {'msg': _('Already approved')} if user.check_approve_token(hash): user.approved = True self.request.session.save() self.request.session['user'] = user return HTTPFound(self.request.route_url('home'), headers=remember(self.request, user.guid)) 

When I try to get the self.request.session['user'] variable from another handler, I get a DetachedInstanceError: Instance <User at 0x42902f0> is not bound to a Session; attribute refresh operation cannot proceed DetachedInstanceError: Instance <User at 0x42902f0> is not bound to a Session; attribute refresh operation cannot proceed . As far as I understand, this error occurs due to the modification of the User instance. How can i fix this?

Thank you Ivan.

+4
source share
1 answer

The error is due to the fact that the model objects ( user ) are managed by the session ( DbSession ). When you store an instance in a session ( request.session ) and then access it again in another request, it uses a different DbSession . Moving a managed entity between sessions is supported, but not automatically. When retrieving an object from request.session you can merge it into a new DbSession via user = DbSession.merge(user) .

http://docs.sqlalchemy.org/en/latest/orm/session.html?highlight=merge#merging

+15
source

Source: https://habr.com/ru/post/1401406/


All Articles