Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change object's attribute on session commit - Flask SQLAlchemy

I want to change an object's attribute before it is inserted to the DB using Falsk-SQLAlachemy. I tried using before_models_committed signal, but it seems to be broken, so I'm trying models_commited instead (and re-committing the changes) and I get the following error:

InvalidRequestError: This session is in 'committed' state; no further SQL can be emitted within this transaction.

The code is provided bellow:

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 of connecting any signals to execute a function whenever a new object is inserted to the DB and save those changes?

Thanks!

like image 979
bsmaniotto Avatar asked Oct 16 '14 20:10

bsmaniotto


1 Answers

Ok, I manage to do it using SQLAlchemy Mapper 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 by this 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 is:

from flask.ext.sqlalchemy import event
like image 62
bsmaniotto Avatar answered Sep 22 '22 20:09

bsmaniotto