3

I'm new to SqlAlchemy. We were working primarily with Flask, but in a particular case I needed a manual database connection. So I launched a new db connection with something like this:

write_engine = create_engine("mysql://user:pass@localhost/db?charset=utf8")
write_session = scoped_session(sessionmaker(autocommit=False,
    autoflush=False,bind=write_engine))

nlabel = write_session.query(Label).filter(Label.id==label.id).first() # Works
#Later in code
ms = Message("Some message")
write_session.add(ms) # Works fine
write_session.commit() # Errors out

Error looks like "AttributeError: 'SessionMaker' object has no attribute '_model_changes'"

What am I doing wrong?

Neo
  • 13,179
  • 18
  • 55
  • 80
  • What does the Message model look like? If you are using the Flask-Sqlalchemy extension, this may come in handy: https://github.com/mitsuhiko/flask-sqlalchemy/pull/89 – aezell Sep 18 '12 at 19:11
  • `write_session` should really be an instance of `Session`, not a `SessionMaker` – Damien Dec 03 '14 at 14:40
  • Related to https://stackoverflow.com/questions/20201809/sqlalchemy-flask-attributeerror-session-object-has-no-attribute-model-chan?lq=1 – Charles L. Mar 05 '19 at 21:58

2 Answers2

3

From the documentation I think you might be missing the initialization of the Session object.

Try:

Session = scoped_session(sessionmaker(autocommit=False, autoflush=False,bind=write_engine))
write_session = Session()

It's a shot in the dark- I'm not intimately familiar with SQLAlchemy. Best of luck!

bm1362
  • 41
  • 3
2

Your issue is that you are missing this line:

db_session._model_changes = {}
  • 4
    please add some explanation of your solution and how it resolves the problem – Our Man in Bananas May 13 '14 at 21:34
  • 1
    @Philip, because flask attaches a static method for the session. Hence, before commit it checks _model_changes. See flask_sqlclchemy's __init__.py. Here is the function:def session_signal_before_commit(session): d = session._model_changes if d: before_models_committed.send(session.app, changes=d.values()) – chfw May 22 '14 at 12:27