Will database callbacks be appended each time model is changed?

45 views
Skip to first unread message

Thomas Sitter

unread,
Jul 29, 2015, 10:59:59 PM7/29/15
to web2py-users
Hello,

I'm adding an _after_update callback to my table in db.py using:

def myfunc(s,f):
  #do stuff
  return False

db
.tt._after_update.append(myfunc)

My question is whether this will continuously append this method every time a database table is modified.

I'm asking because I had a similar issue when creating the initial auth users/groups in db.py. I had to wrap the code in the following logic to prevent them being added multiple times

if not db().select(db.auth_user.ALL).first():
  group_1 = auth.add_group('group1', 'group1 employees')
  ...


Thanks

Anthony

unread,
Jul 30, 2015, 12:50:49 AM7/30/15
to web2py-users, thomas...@gmail.com, thomas...@gmail.com
auth.add_group() actually does a database insert, so you don't want to keep repeating it on every request (actually, I would probably move that code out of the app altogether, as it really only needs to be run once ever).

Specifying the after update callback, on the other hand, does not affect the database at all -- it simply tells the DAL what to do after a database update. In fact, you need this to run on every request because it is part of the model definition (for the same reason you need to run the associated db.define_table() on every request).

Anthony

Thomas Sitter

unread,
Jul 30, 2015, 11:01:51 AM7/30/15
to web2py-users, abas...@gmail.com
Sorry I should have clarified my question.

The part I'm concerned about is the use of append when adding the callback. If append is being used is there any check to make sure a function is not already in the list. I do not want to call the same callback multiple times when a record is updated.

In the sourcecode _after_callback is implemented as a list and I see no checks to make sure the same function isn't inserted/called more than once. Perhaps it should be a set?

Anthony

unread,
Jul 30, 2015, 11:09:07 AM7/30/15
to web2py-users, thomas...@gmail.com, thomas...@gmail.com
Same answer. Each request is handled in a separate thread, so any code in a model, controller, or view is run in a fresh environment. When you define a table or specify callbacks in a model file, it's like it is happening for the first time (as it only applies to the current request) -- it is not as if a new copy of your callback function is being appended to an ever-growing list on every request. You would only be appending the same function twice if your code includes:

db.tt._after_update.append(myfunc)

in two separate places.

Anthony

Thomas Sitter

unread,
Jul 30, 2015, 11:52:40 AM7/30/15
to web2py-users, abas...@gmail.com
Thank you, that clarifies things for me.
Reply all
Reply to author
Forward
0 new messages