SQLAlchemy-Continuum 和金字塔:UnboundExecutionError

SQLAlchemy-Continuum and Pyramid: UnboundExecutionError

我有一个Pyramid application that does CRUD with SQLAlchemy via pyramid_basemodel。一切似乎都很好。

然后我安装了 pip SQLAlchemy-Continuum,以提供某些对象的历史记录。我所做的就是对我的 models.py 文件进行以下更改:

import sqlalchemy as sa
from sqlalchemy import (event, Column, Index, Integer, Text, String, Date, DateTime, \
    Float, ForeignKey, Table, Boolean,)
from sqlalchemy.orm import (relationship, backref, mapper, scoped_session, sessionmaker,)

from pyramid_basemodel import Base, BaseMixin, Session, save
from pyramid_fullauth.models import User
from sqlalchemy_continuum import make_versioned

from colanderalchemy import setup_schema
from zope.sqlalchemy import ZopeTransactionExtension

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
event.listen(mapper, 'mapper_configured', setup_schema)

# Continuum setup
make_versioned()

# FOR EACH VERSIONED MODEL I ADD __versioned__ = {} at the start of each model def. Eg:
class Thing(Base):
    __versioned__ = {}
    __tablename__ = 'thing'
    id = sa.Column(Integer, primary_key=True)
    related_id = sa.Column(Integer, ForeignKey('OtherThing.id'))
    other_thing = sa.orm.relationship("OtherThing", backref="thing")
    description = sa.Column(String(length=100))
    a_date = sa.Column(Date)
    some_hours = sa.Column(Integer)
    b_date = sa.Column(Date)
    more_hours = sa.Column(Integer)


sa.orm.configure_mappers()

(对于略微多余的导入,我深表歉意;我决定完全遵循 Continuum 示例和 import sqlalchemy as sa,并在我版本化的模型中切换到使用该表示法。我也可能是基于对不同教程的半理解,做愚蠢的、猴子看猴子做的事情。)

此设置允许我 运行 alembic revision --autogenerate 并在数据库中生成 ModelHistory 表,但是当我转到某些读取现在版本化模型的页面时,它们给出了错误

sqlalchemy.exc.UnboundExecutionError: This session is not bound to a single Engine or Connection, and no context was provided to locate a binding.

由于某种原因,它读取了一个以相同方式添加的模型,但随后尝试更新它失败并出现相同的错误。

我的猜测是我需要配置 Continuum 用于 SQLAlchemy 会话的任何内容以指向 Pyramid 中配置的现有会话,但我不确定。我暖和了吗?

您在调用时正在生成一个会话:

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))

但未将其绑定到引擎。您的金字塔模板 pyramid_basemodel 已经为您生成会话并将其绑定到引擎。

尝试删除 DBSession 并使用从 pyramid_basemodel 导入的 Session。