Change an attribute of an object during a session - SQLAlchemy flag

I want to change the attribute of an object before inserting it into the database using Falsk-SQLAlachemy. I tried using the before_models_committed signal, but it seems to be broken, so I try to use mod_commited instead (and override the changes), and I get the following error:

InvalidRequestError: this session is in the "commit" state; no further SQL can be released as part of this transaction.

The code is below:

from app import db from app import app from flask.ext.sqlalchemy import models_committed class Foo(db.Model): id = db.Column(db.Integer, primary_key=True) foo_attr = db.Column(db.String(128), index=True) def on_models_committed(app, changes): for change in changes: foo_obj = change[0] operation = change[1] if foo_obj.__class__.__name__ == 'Foo': if operation == 'insert': foo_obj.foo_attr = get_new_value() db.session.add(foo_obj) db.session.commit() models_committed.connect(on_models_committed) 

Is there a way to connect any signals to execute a function whenever a new object is inserted into the database and saves these changes?

Thanks!

+7
python flask flask-sqlalchemy
source share
1 answer

Well, I succeed using SQLAlchemy mapping events.

This code:

 def on_models_committed(app, changes): for change in changes: foo_obj = change[0] operation = change[1] if foo_obj.__class__.__name__ == 'Foo': if operation == 'insert': foo_obj.foo_attr = get_new_value() db.session.add(foo_obj) db.session.commit() models_committed.connect(on_models_committed) 

should be replaced with the following code:

 def on_foo_created(mapper, connection, foo_obj): foo_obj.foo_attr = get_new_value() event.listen(Foo, 'before_insert', on_foo_created) 

And the new import statement:

 from flask.ext.sqlalchemy import event 
+3
source share

All Articles