我编写了自己的 PyramidISession
接口实现,它应该将 Session 存储在数据库中。一切都很好,但不知何故pyramid_tm
抛出了这个。一旦激活它就会说:
DetachedInstanceError: Instance <Session at 0x38036d0> is not bound to a Session;
attribute refresh operation cannot proceed
(不要在这里混淆:The<Session ...>
是模型的类名,“... to a Session”很可能是指 SQLAlchemy 的 Session(我称之为DBSession
避免混淆)。
我查看了邮件列表和 SO,似乎任何时候有人遇到问题,他们是
- 产生一个新线程或
- 手动调用
transaction.commit()
这些事情我都不做。然而,这里的特点是,我的会话被 Pyramid 传递了很多。首先我做DBSession.add(session)
然后return session
。之后我可以处理会话,显示新消息等。
但是,似乎一旦请求完成,我就会收到此异常。这是完整的回溯:
Traceback (most recent call last):
File "/home/javex/data/Arbeit/libraries/python/web_projects/pyramid/lib/python2.7/site-packages/waitress-0.8.1-py2.7.egg/waitress/channel.py", line 329, in service
task.service()
File "/home/javex/data/Arbeit/libraries/python/web_projects/pyramid/lib/python2.7/site-packages/waitress-0.8.1-py2.7.egg/waitress/task.py", line 173, in service
self.execute()
File "/home/javex/data/Arbeit/libraries/python/web_projects/pyramid/lib/python2.7/site-packages/waitress-0.8.1-py2.7.egg/waitress/task.py", line 380, in execute
app_iter = self.channel.server.application(env, start_response)
File "/home/javex/data/Arbeit/libraries/python/web_projects/pyramid/lib/python2.7/site-packages/pyramid/router.py", line 251, in __call__
response = self.invoke_subrequest(request, use_tweens=True)
File "/home/javex/data/Arbeit/libraries/python/web_projects/pyramid/lib/python2.7/site-packages/pyramid/router.py", line 231, in invoke_subrequest
request._process_response_callbacks(response)
File "/home/javex/data/Arbeit/libraries/python/web_projects/pyramid/lib/python2.7/site-packages/pyramid/request.py", line 243, in _process_response_callbacks
callback(self, response)
File "/home/javex/data/Arbeit/libraries/python/web_projects/pyramid/miniblog/miniblog/models.py", line 218, in _set_cookie
print("Setting cookie %s with value %s for session with id %s" % (self._cookie_name, self._cookie, self.id))
File "build/bdist.linux-x86_64/egg/sqlalchemy/orm/attributes.py", line 168, in __get__
return self.impl.get(instance_state(instance),dict_)
File "build/bdist.linux-x86_64/egg/sqlalchemy/orm/attributes.py", line 451, in get
value = callable_(passive)
File "build/bdist.linux-x86_64/egg/sqlalchemy/orm/state.py", line 285, in __call__
self.manager.deferred_scalar_loader(self, toload)
File "build/bdist.linux-x86_64/egg/sqlalchemy/orm/mapper.py", line 1668, in _load_scalar_attributes
(state_str(state)))
DetachedInstanceError: Instance <Session at 0x7f4a1c04e710> is not bound to a Session; attribute refresh operation cannot proceed
对于这种情况,我停用了调试工具栏。一旦我激活它,错误就会从那里抛出。似乎这里的问题是在任何时候访问对象。
我意识到我可以尝试以某种方式分离它,但这似乎不是正确的方法,因为如果不再次明确地将其添加到会话中,就无法修改元素。
因此,当我没有产生新线程并且我没有显式调用提交时,我猜事务在请求完全消失之前提交,然后再次访问它。我该如何处理这个问题?