ZCML directives

Components may be registered using the registration API exposed by zope.component (provideAdapter, provideUtility, etc.). They may also be registered using configuration files. The common way to do that is by using ZCML (Zope Configuration Markup Language), an XML spelling of component registration.

In ZCML, each XML element is a directive. There are different top-level directives that let us register components. We will introduce them one by one here.

This helper will let us easily execute ZCML snippets:

adapter

Adapters play a key role in the Component Architecture. In ZCML, they are registered with the <adapter /> directive.

Before we register the first test adapter, we can verify that adapter lookup doesn’t work yet:

Then we register the adapter and see that the lookup works:

It is also possible to give adapters names. Then the combination of required interface, provided interface and name makes the adapter lookup unique. The name is supplied using the name argument to the <adapter /> directive:

Adapter factories

It is possible to supply more than one adapter factory. In this case, during adapter lookup each factory will be called and the return value will be given to the next factory. The return value of the last factory is returned as the result of the adapter lookup. For examle:

The resulting adapter is an A3, around an A2, around an A1, around the adapted object:

Of course, if no factory is provided at all, we will get an error:

Declaring for, provides and name in Python

The <adapter /> directive can figure out from the in-line Python declaration (using zope.component.adapts() or zope.component.adapter(), zope.interface.implements as well as zope.component.named) what the adapter should be registered for and what it provides:

Of course, if the adapter has no implements() declaration, ZCML can’t figure out what it provides:

On the other hand, if the factory implements more than one interface, ZCML can’t figure out what it should provide either:

Let’s now register an adapter that has a name specified in Python:

>>> runSnippet('''
...   <adapter factory="zope.component.testfiles.components.Comp4" />''')
>>> zope.component.getAdapter(Content(), IApp, 'app').__class__
<class 'zope.component.testfiles.components.Comp4'>

A not so common edge case is registering adapters directly for classes, not for interfaces. For example:

This time, any object providing IContent won’t work if it’s not an instance of the Content class:

Multi-adapters

Conventional adapters adapt one object to provide another interface. Multi-adapters adapt several objects at once:

You can even adapt an empty list of objects (we call this a null-adapter):

Even with multi-adapters, ZCML can figure out the for and provides parameters from the Python declarations:

Chained factories are not supported for multi-adapters, though:

And neither for null-adapters:

Protected adapters

Adapters can be protected with a permission. First we have to define a permission for which we’ll have to register the <permission /> directive:

We see that the adapter is a location proxy now so that the appropriate permissions can be found from the context:

We can also go about it a different way. Let’s make a public adapter and wrap the adapter in a security proxy. That often happens when an adapter is turned over to untrusted code:

Of course, this still works when we let the ZCML directive handler figure out for and provides from the Python declarations:

It also works with multi adapters:

It’s probably not worth mentioning, but when we try to protect an adapter with a permission that doesn’t exist, we’ll obviously get an error:

Trusted adapters

Trusted adapters are adapters that are trusted to do anything with the objects they are given so that these objects are not security-proxied. They are registered using the trusted argument to the <adapter /> directive:

With an unproxied object, it’s business as usual:

With a security-proxied object, however, we get a security-proxied adapter:

While the adapter is security-proxied, the object it adapts is now proxy-free. The adapter has umlimited access to it:

We can also protect the trusted adapter with a permission:

Again, with an unproxied object, it’s business as usual:

With a security-proxied object, we again get a security-proxied adapter:

Since we protected the adapter with a permission, we now encounter a location proxy behind the security proxy:

There’s one exception to all of this: When you use the public permission (zope.Public), there will be no location proxy:

We can also explicitply pass the locate argument to make sure we get location proxies:

subscriber

With the <subscriber /> directive you can register subscription adapters or event subscribers with the adapter registry. Consider this very typical example of a <subscriber /> directive:

Note how ZCML provides some additional information when registering components, such as the ZCML filename and line numbers:

The “fun” behind subscription adapters/subscribers is that when several ones are declared for the same for/provides, they are all found. With regular adapters, the most specific one (and in doubt the one registered last) wins. Consider these two subscribers:

Declaring for and provides in Python

Like the <adapter /> directive, the <subscriber /> directive can figure out from the in-line Python declaration (using zope.component.adapts() or zope.component.adapter()) what the subscriber should be registered for:

In the same way the directive can figure out what a subscriber provides:

A not so common edge case is declaring subscribers directly for classes, not for interfaces. For example:

This time, any object providing IContent won’t work if it’s not an instance of the Content class:

Protected subscribers

Subscribers can also be protected with a permission. First we have to define a permission for which we’ll have to register the <permission /> directive:

Trusted subscribers

Like trusted adapters, trusted subscribers are subscribers that are trusted to do anything with the objects they are given so that these objects are not security-proxied. In analogy to the <adapter /> directive, they are registered using the trusted argument to the <subscriber /> directive:

With an unproxied object, it’s business as usual:

Now with a proxied object. We will see that the subscriber has unproxied access to it, but the subscriber itself is proxied:

There’s no location proxy behind the security proxy:

If you want the trusted subscriber to be located, you’ll also have to use the locate argument:

Again, it’s business as usual with an unproxied object:

With a proxied object, we again get a security-proxied subscriber:

However, thanks to the locate argument, we now have a location proxy behind the security proxy:

Event subscriber (handlers)

Sometimes, subscribers don’t need to be adapters that actually provide anything. It’s enough that a callable is called for a certain event.

In this case, simply getting the subscribers is enough to invoke them:

utility

Apart from adapters (and subscription adapters), the Component Architecture knows a second kind of component: utilities. They are registered using the <utility /> directive.

Before we register the first test utility, we can verify that utility lookup doesn’t work yet:

Then we register the utility:

Like adapters, utilities can also have names. There can be more than one utility registered for a certain interface, as long as they each have a different name.

First, we make sure that there’s no utility yet:

Then we register it:

Utilities can also be registered from a factory. In this case, the ZCML handler calls the factory (without any arguments) and registers the returned value as a utility. Typically, you’d pass a class for the factory:

Declaring provides in Python

Like other directives, <utility /> can also figure out which interface a utility provides from the Python declaration:

It won’t work if the component that is to be registered doesn’t provide anything:

Or if more than one interface is provided (then the ZCML directive handler doesn’t know under which the utility should be registered):

We can repeat the same drill for utility factories:

Declaring name in Python

Let’s now register a utility that has a name specified in Python:

>>> runSnippet('''
...   <utility component="zope.component.testfiles.components.comp4" />''')
>>> from zope.component.testfiles.components import comp4
>>> zope.component.getUtility(IApp, name='app') is comp4
True
>>> runSnippet('''
...   <utility factory="zope.component.testfiles.components.Comp4" />''')
>>> zope.component.getUtility(IApp, name='app') is comp4
False
>>> zope.component.getUtility(IApp, name='app').__class__
<class 'zope.component.testfiles.components.Comp4'>

Protected utilities

TODO:

def testProtectedUtility(self):
    """Test that we can protect a utility.

    Also:
    Check that multiple configurations for the same utility and
    don't interfere.
    """
    self.assertEqual(zope.component.queryUtility(IV), None)
    xmlconfig(StringIO(template % (
        '''
        <permission id="tell.everyone" title="Yay" />
        <utility
          component="zope.component.testfiles.components.comp"
          provides="zope.component.testfiles.components.IApp"
          permission="tell.everyone"
          />
        <permission id="top.secret" title="shhhh" />
        <utility
          component="zope.component.testfiles.components.comp"
          provides="zope.component.testfiles.components.IAppb"
          permission="top.secret"
          />
        '''
        )))

    utility = ProxyFactory(zope.component.getUtility(IApp))
    items = getTestProxyItems(utility)
    self.assertEqual(items, [('a', 'tell.everyone'),
                             ('f', 'tell.everyone')
                             ])
    self.assertEqual(removeSecurityProxy(utility), comp)

def testUtilityUndefinedPermission(self):
    config = StringIO(template % (
         '''
         <utility
          component="zope.component.testfiles.components.comp"
          provides="zope.component.testfiles.components.IApp"
          permission="zope.UndefinedPermission"
          />
        '''
        ))
    self.assertRaises(ValueError, xmlconfig, config,
                      testing=1)

interface

The <interface /> directive lets us register an interface. Interfaces are registered as named utilities. We therefore needn’t go though all the lookup details again, it is sufficient to see whether the directive handler emits the right actions.

First we provide a stub configuration context:

Then we provide a test interface that we’d like to register:

It doesn’t yet provide ITestType:

However, after calling the directive handler…

…it does provide ITestType: