Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyramid / SQL Alchemy DetachedInstanceError

I'm trying to implement email confirmation using Pyramid framework. Here's the code that confirms the user in the database and redirects them to the home 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. As far as I understand, this error raised because of the modification of User instance. How can I fix it?

Thanks in advance, Ivan.

like image 455
Ivan Gromov Avatar asked Dec 09 '22 01:12

Ivan Gromov


1 Answers

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

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

like image 197
Michael Merickel Avatar answered Dec 26 '22 21:12

Michael Merickel