[Flask] after_insert question

Craig Amundsen amundsen.craig at gene.com
Tue Jun 7 18:12:08 EDT 2016

I thought I might answer my own question.

I haven't been able to get an elegant solution to this problem. I can get
the before_insert and before_update events to do things, but the only way I
can get a change in my Foo table to show end up with a new row in the Bar
table is to use the connection object's execute method to run some SQL. I
didn't like that.

The final problem I had with this method is that I need to write the Foo
row's primary key into the Bar row. before_insert fires before the Foo row
has a primary key.

What I did instead was a bit of a kludge, but in my new_foo and edit_foo
view methods I call a static method Bar.saveFoo(foo_instance) which creates
a new Bar row. I know I could do this with database triggers, but I don't
want tie myself to a particular database

On Fri, Jun 3, 2016 at 9:38 AM, Craig Amundsen <amundsec at gene.com> wrote:

> Hi -
> I'm trying to use an after_insert event to do some bookkeeping in a Flask
> app and am having issues.
> Before we get too far I've been basing my app on the Grinberg Flask Web
> Development book.
> Simplifying wildly, lets say I have these two tables
> class Foo(db.Model)
>     __tablename__ = 'foos'
>     id = db.Column(db.Integer, primary_key = True)
>     col_one = db.Column(db.String(32))
>     col_two = db.Column(db.String(32))
>     @staticmethod
>     def on_change(mapper, connection, target):
>         # save a new row in table Bar
> class Bar(db.Model)
>     __tablename__ = 'bars'
>     id = db.Column(db.Integer, primary_key = True)
>     col_a = db.Column(db.Integer)
>     col_b = db.Column(db.String(16))
> db.event.isent(Foo, 'after_insert', Foo.on_change)
> I really only want to add the row to Bar if there is an actual write to
> Foo.
> I note that if I make the listened-for event before_insert and in the
> on_change method I do
> b = Bar(col_a = 5, col_b = 'Hi Craig')
> db.session.add(b)
> I get shouty messages in the console, but it works.
> I see various things when I google for using the connection object in an
> after_insert event, but nothing that is actually a workable example that I
> can transmogrify for my actual use.
> I could put something in the new_foo method in views.py that writes a Bar
> entry, but I'd like to use the event.
> Could someone point me in the proper direction for getting a
> connection.execute call to work?
> Thanks,
> - Craig
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/flask/attachments/20160607/5aaffc74/attachment.html>

More information about the Flask mailing list