It's really easy to miss why a utility is so useful in a web application.  Why not just use a function, or perhaps a object factory instead?

Process flow for web applications is initiated by a request.  For Grok and Zope, the request is served by a handler function in the module zope.publisher.publish called (wait for it...) publish.  This traverses the data path, locates and instantiates the data object which is the context for the request, and calls the appropriate views/adapter objects or callables for the context.  When the HTML (or other) content is returned by the view, the whole stack is unwound again.

It is simply not efficient, in many cases, to repeat the entire build up and tear down for each and every request.  That's why we have a web framework, and don't just use CGI. 

Imagine for example having to open and close a database connection for every request!

Database connection pools may be managed very easily as a global utility, but that is just by way of example.

Utilities to the rescue!

Utilities are singleton objects registered with the component framework.  The lookup and instantiation for these objects is highly optimised.  There are two kinds of utilities: global, and local.

A global utility provides a specific interface, and is initialised once only, at registration time, whenever the application is run.  Because the initialisation is not repeated every time it is accessed, a utility can be implemented in a very efficient way.  Global utilities are differentiated by name or by interface

It is also easy to replace standard behaviour by overriding the implementation of a global utility, since there can only be one utility registered at a time for a given interface and name; you just plug in your own component in the interface slot.

Much of the behaviour of global utilities applies to local utilities, except that local utilities are only ever initialised once, at the time they are created and installed.  Within the Grok framework, multiple applications (or sites) can be active at any time, and local utilities are specific to, and the utility object stored persistently within a particular site.   A good example for a local utility would be an authentication database containing user account and authorization data.

Grok sites are always instances of grok.Application objects (or more accurately implementors of the ISITE interface) stored inside the ZODB tree for a given framework instance.

Both global and local utilities are easily (and very quickly) found by either a call to zope.component.getUtility() or zope.component.queryUtility().

 

Grok 4 Noobs

The amazingly useful Utility