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

后端 未结 2 1169
鱼传尺愫
鱼传尺愫 2020-12-31 03:40

I\'ve seen a lot of problems with SessionMaker, but this one is slightly different. Not sure why, but sqlalchemy won\'t let my session object commit.

In my app, I h

相关标签:
2条回答
  • 2020-12-31 04:24

    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.

    0 讨论(0)
  • 2020-12-31 04:29

    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

    0 讨论(0)
提交回复
热议问题