On Nov 26, 2013, at 3:41 AM, George Sakkis <[email protected]> wrote:
> > > On Monday, 25 November 2013 17:27:02 UTC+2, Michael Bayer wrote: > > On Nov 25, 2013, at 9:00 AM, George Sakkis <[email protected]> wrote: > > > Hi all, > > > > is there a feature or pattern for adding a listener that is to be executed > > (at most) once? For example, say you want to send an email when user is > > created and the session is committed. If event.listen() supported a "once" > > boolean parameter, this could be expressed as: > > > > def email_user(email_address, message): > > ... > > ... > > if valid_data: > > new_user = User(**valid_data) > > db.session.add(new_user) > > # send an email to new_user after committing > > event.listen(db.session, "after_commit", > > once=True, # hypothetical parameter > > lambda session: email_user(new_user.email, "welcome > > {}!".format(new_user.name)) > > there are certain events such as pool.first_connect that use a “once” type of > system, but that is linked to the type of event. > > I haven’t tried this but you should be able to call event.remove() > (sqlalchemy 0.9) within the handler: > > def go(session): > email_user(…) > event.remove(session, “after_commit”, go) > event.listen(session, “after_commit”, go) > > Nice, this should do the trick, thanks. Any workaround for 0.7.x-0.8.x ? you have to have your event listener itself have some kind of flag or state that affects it on the next go-around. _done = [False] @event.listens_for(…) def my_event(…): if not _done[0]: _done[0] = True # do event > > George > > > > > -- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email [email protected]. > To post to this group, send email to [email protected]. > Visit this group at http://groups.google.com/group/sqlalchemy. > For more options, visit https://groups.google.com/groups/opt_out.
signature.asc
Description: Message signed with OpenPGP using GPGMail
