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

后端 未结 2 1187
鱼传尺愫
鱼传尺愫 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: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

提交回复
热议问题