烧瓶& SqlAlchemy - alembic session.add_all()导致AttributeError:'bool'对象没有属性'clear'错误

时间:2014-07-16 17:44:41

标签: python flask sqlalchemy flask-sqlalchemy alembic

我正在尝试插入一些数据作为部署的一部分。我创建了以下alembic修订脚本

revision = '59891ffc8502'
down_revision = '349540cf9cef'

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship

Session = sessionmaker()
Base = declarative_base()

class Colours(Base):
    __tablename__ = 'colours'

    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column('name', sa.Unicode(length=25), nullable=False)
    code = sa.Column('code', sa.Unicode(length=2), nullable=False)


def upgrade():
    bind = op.get_bind()
    session = Session(bind=bind)
    session._model_changes = False

    op.alter_column('colours', 'code', new_column_name='code', existing_type=mysql.VARCHAR(length=25))

    col = [ 
            { "name": "Black", "code": "ff00cc" }, 
            { "name": "Blue", "code": "ff00cc" }, 
            { "name": "Brown", "code": "ff00cc" }, 
            { "name": "Gold", "code": "ff00cc" }, 
            { "name": "Green", "code": "ff00cc" }
    ]

    # populate colours table
    colours = { c['name']: Colours(name=unicode(c['name']), code=c['code']) for c in col}
    session.add_all(colours.values())

    session.commit()
    # ### end Alembic commands ###

并在AttributeError中升级head结果:'bool'对象没有属性'clear'错误。 任何线索?

1 个答案:

答案 0 :(得分:1)

事实证明,设置session._model_changes = False并不足以解决Flask-SQLAlchemy问题。您需要完全取消注册它注册的事件处理程序。

from flask_sqlalchemy import _SessionSignalEvents
from sqlalchemy import event
from sqlalchemy.orm import Session as BaseSession

Session = sessionmaker()

event.remove(BaseSession, 'before_commit', _SessionSignalEvents.session_signal_before_commit)
event.remove(BaseSession, 'after_commit', _SessionSignalEvents.session_signal_after_commit)
event.remove(BaseSession, 'after_rollback', _SessionSignalEvents.session_signal_after_rollback)