sqlalchemy flask: AttributeError: 'Session' object has no attribute '_model_changes' on session.commit()

a 夏天 提交于 2019-11-30 08:24:17

Yes this is exactly problem when using flask-sqlalchemy models mixed with pure sqlalchemy session. Thing is that flask-sqlalchemy subclasses the base Session from sqlalchemy and adds some internals one of which is the _model_changes dict. This dict is used for model modification tracking.

So if you want to use flask-sqlalchemy based models with regular sqlalchemy session, one way would be to just add the dict to the session (this is just example code):

def create_session(config):
    engine = create_engine(config['DATABASE_URI'])
    Session = sessionmaker(bind=engine)
    session = Session()
    session._model_changes = {}
    return session 

I had the same exact problem as you, so hopefully this should help you.

UPDATE:

There is new version available, which should be fixing this behaviour, quoting the 2.0 docs:

Changed how the builtin signals are subscribed to skip non Flask-SQLAlchemy sessions. This will also fix the attribute error about model changes not existing.

Docs: http://flask-sqlalchemy.pocoo.org/2.0/changelog/#version-2-0

I had the same problem as well, and solved it by modifying the _SessionSignalEvents class within init.py in flask-sqlalchemy. However, I just noticed that such a fix had already been in place since 8 months on the official repository.

If you encounter a similar problem, I would recomment you to pull the latest version of the project off github (https://github.com/mitsuhiko/flask-sqlalchemy/) since the one currently available through pip install is outdated.

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