Sometimes there is a need to perform actions based on other actions which might occur, such as a need to update a search index whenever an item is added to a container object.

The ZCA event mechanism provides a way to do precisely that.  By listening for "add" events to a container, and having inserts to that container trigger an "add" event, one can easily extend the behaviour of the container.

Zope already provides a number of events for standard components, for example:

zope.component.interfaces.IRegistrationEvent
zope.component.interfaces.IAdapterRegistration
zope.component.interfaces.IHandlerRegistration
zope.component.interfaces.ISubscriptionAdapterRegistration
zope.component.interfaces.IUtilityRegistration

and it is easy enough to add your own.

from zope.component.interfaces import IObjectEvent, ObjectEvent


class IMyProcessingDoneEvent(IObjectEvent):
    ''' An event to trigger after processing '''


class MyProcessingDoneEvent(ObjectEvent):
    grok.implements(IMyProcessingDoneEvent)


class MyApp(grok.Application, grok.Container):

    def do_index(self, ev):
        '''  Do some indexing '''
        ...
        grok.notify(MyProcessingDoneEvent(self))


@grok.subscribe(MyApp, grok.IObjectAddedEvent)
def newItem(app, event):
    ''' A new item was added '''
    app.do_index(event)

@grok.subscribe(MyApp, IMyProcessingDoneEvent)
def processingDone(app, event):
    ''' Do stuff after processing is finished'''
    ...

 Events are useful when dealing with asynchronicity.  For example, the framework might at some point during startup need to configure a database.  You can define a handler for this event like this:

from megrok import rdb

...

metadata = rdb.MetaData()

@grok.subscribe(IEngineCreatedEvent)
def create_engine_created(event):
    rdb.setupDatabase(metadata)

 For a fuller example of setting up SQLAlchemy, see here.

Note that the asynchronous nature of events does not imply that event handlers run in their own thread.  When the handler is called, the caller waits for the event handler to complete before continuing.

 

Grok 4 Noobs

Events Mechanism