Zope Process Lifetime

4.0 · active · verified Fri Apr 17

zope.processlifetime provides an API for registering subscribers to events occurring during a process's lifecycle, such as starting, initialized, and stopping. It is a core component of the Zope Toolkit, enabling robust resource management and cleanup in Zope-based applications. The current version is 4.0, with releases typically following major Python version updates or Zope Foundation initiatives.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define handler functions and register them with `zope.processlifetime.registerProcessSubscriber` for specific process lifecycle events. It also shows how to explicitly dispatch these events using `zope.event.notify` for testing purposes, which is typically handled automatically by a Zope application server in a production environment.

import os
from zope.processlifetime import registerProcessSubscriber, IProcessStarting, IProcessInitialized, IProcessStopping
from zope.interface import implementer
import zope.event # Required for dispatching events

# Define handler functions that will react to events
def handle_startup(event):
    print("Process starting event received!")
    # Typically, you would initialize resources here
    assert isinstance(event, IProcessStarting)

def handle_initialized(event):
    print("Process initialized event received!")
    # Typically, you would confirm readiness or start background tasks here
    assert isinstance(event, IProcessInitialized)

def handle_stopping(event):
    print("Process stopping event received!")
    # Typically, you would clean up resources or save state here
    assert isinstance(event, IProcessStopping)

# Register the handler functions for the respective lifecycle interfaces
registerProcessSubscriber(handle_startup, IProcessStarting)
registerProcessSubscriber(handle_initialized, IProcessInitialized)
registerProcessSubscriber(handle_stopping, IProcessStopping)

print("Subscribers registered. Now simulating event dispatch:")

# In a real Zope application, a framework or server would dispatch these events.
# For demonstration, we create and notify them explicitly using zope.event.

# Define simple event objects that implement the interfaces
@implementer(IProcessStarting)
class ProcessStartingEvent: pass

@implementer(IProcessInitialized)
class ProcessInitializedEvent: pass

@implementer(IProcessStopping)
class ProcessStoppingEvent: pass

# Dispatch the events to trigger the registered handlers
zope.event.notify(ProcessStartingEvent())
zope.event.notify(ProcessInitializedEvent())
zope.event.notify(ProcessStoppingEvent())

print("\nEvents dispatched. Check console output for handler messages.")
# Note: os.environ.get('AUTH_KEY', '') is not relevant for this library's quickstart.

view raw JSON →