Pyramid / SQL Alchemy DetachedInstanceError

浪尽此生 提交于 2019-12-10 08:17:47

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/9704927/pyramid-sql-alchemy-detachedinstanceerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!