金字塔/SQL Alchemy DetachedInstanceError [英] Pyramid / SQL Alchemy DetachedInstanceError

查看:56
本文介绍了金字塔/SQL Alchemy DetachedInstanceError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Pyramid 框架实现电子邮件确认.这是在数据库中确认用户并将其重定向到主页的代码.

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))

当我尝试从另一个处理程序获取 self.request.session['user'] 变量时,我得到一个 DetachedInstanceError: Instance <User at 0x42902f0>不受会话的约束;属性刷新操作无法继续.据我了解,这个错误是由于 User 实例的修改引起的.我该如何解决?

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?

提前致谢,伊万.

推荐答案

该错误是因为模型对象 (user) 由会话 (DbSession) 管理.当您将实例存储在会话 (request.session) 中,然后在另一个请求中再次访问它时,这是使用不同的 DbSession.支持在会话之间移动托管对象,但不会自动支持.从 request.session 检索对象时,您可以通过 user = DbSession.merge(user) 将其合并到新的 DbSession 中.

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

这篇关于金字塔/SQL Alchemy DetachedInstanceError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆