asynchronous - Saving/inserting multiple records with Python Twistar -
extending twistar example code, i'm trying write multiple records @ once:
from twisted.enterprise import adbapi twistar.registry import registry twistar.dbobject import dbobject twisted.internet import reactor class user(dbobject): pass def done(user): print "a user created name %s" % user.first_name #the example calls reactor.stop() here registry.dbpool = adbapi.connectionpool('mysqldb', user="twistar", passwd="apass", db="twistar") # i've added function: def write_user(first_name) u = user(first_name=first_name) u.save().addcallback(done) new_users = ["alice","bob"] new_user in new_users: #here's call function repeatedly: write_user(new_user) reactor.run()
as is, example prints:
a user created name alice user created name bob
but program never exits! adding reactor.stop()
done()
function causes script exit after printing just
a user created name alice
so that's not right, both records added database, anyway.
how should doing this?
first, need return defer of u.save()
that:
def write_user(first_name) u = user(first_name=first_name) return u.save()
then, in loop when write_user
, need store deferred:
results = [] new_user in new_users: results.append(write_user(new_user)) # here, deferred except last 1 call done. deferredlist(results[:-1]).addcallback(done) # here, last deferred call reactor.stop after he's done. results[-1].addcallback(done).addcallback(reactor.stop)
with this, can close reactor when last user has been saved.