[Checkins] SVN: Sandbox/faassen/zope.site/trunk/src/zope/site/ Remove more stuff that isn't relevant to zope.site.
Martijn Faassen
faassen at infrae.com
Tue Jan 27 07:11:21 EST 2009
Log message for revision 95137:
Remove more stuff that isn't relevant to zope.site.
Changed:
U Sandbox/faassen/zope.site/trunk/src/zope/site/__init__.py
D Sandbox/faassen/zope.site/trunk/src/zope/site/meta.zcml
D Sandbox/faassen/zope.site/trunk/src/zope/site/metaconfigure.py
D Sandbox/faassen/zope.site/trunk/src/zope/site/metadirectives.py
D Sandbox/faassen/zope.site/trunk/src/zope/site/vocabulary.py
-=-
Modified: Sandbox/faassen/zope.site/trunk/src/zope/site/__init__.py
===================================================================
--- Sandbox/faassen/zope.site/trunk/src/zope/site/__init__.py 2009-01-27 12:08:18 UTC (rev 95136)
+++ Sandbox/faassen/zope.site/trunk/src/zope/site/__init__.py 2009-01-27 12:11:21 UTC (rev 95137)
@@ -22,43 +22,6 @@
_marker = object()
-# BBB: Deprecated on 9/26/2006
- at zope.deprecation.deprecate('''This function has been deprecated and will go
-away in Zope 3.6. There is no replacement for this function, since it does not
-make sense in light of registry bases anymore. If you are using this function
-to lookup the next utility, consider using get/queryNextUtility. Otherwise, it
-is suggested to iterate through the list of bases of a registry manually.''')
-def getNextSiteManager(context):
- """Get the next site manager."""
- sm = queryNextSiteManager(context, _marker)
- if sm is _marker:
- raise zope.component.interfaces.ComponentLookupError(
- "No more site managers have been found.")
- return sm
-
-
-# BBB: Deprecated on 9/26/2006
- at zope.deprecation.deprecate('''This function has been deprecated and will go
-away in Zope 3.6. There is no replacement for this function, since it does not
-make sense in light of registry bases anymore. If you are using this function
-to lookup the next utility, consider using get/queryNextUtility. Otherwise, it
-is suggested to iterate through the list of bases of a registry manually.''')
-def queryNextSiteManager(context, default=None):
- """Get the next site manager.
-
- If the site manager of the given context is the global site manager, then
- `default` is returned.
- """
- sm = zope.component.getSiteManager(context)
- if sm is zope.component.getGlobalSiteManager():
- return default
-
- bases = sm.__bases__
- if not bases:
- return zope.component.getGlobalSiteManager()
- return bases[0]
-
-
def getNextUtility(context, interface, name=''):
"""Get the next available utility.
Deleted: Sandbox/faassen/zope.site/trunk/src/zope/site/meta.zcml
===================================================================
--- Sandbox/faassen/zope.site/trunk/src/zope/site/meta.zcml 2009-01-27 12:08:18 UTC (rev 95136)
+++ Sandbox/faassen/zope.site/trunk/src/zope/site/meta.zcml 2009-01-27 12:11:21 UTC (rev 95137)
@@ -1,58 +0,0 @@
-<configure
- xmlns="http://namespaces.zope.org/zope"
- xmlns:meta="http://namespaces.zope.org/meta">
-
- <include package="zope.component" file="meta.zcml" />
-
- <meta:directives namespace="http://namespaces.zope.org/zope">
-
- <meta:directive
- name="view"
- schema=".metadirectives.IViewDirective"
- handler="zope.app.component.metaconfigure.view"
- />
-
- <!-- BBB: Deprecated. Will go away in 3.3 -->
- <meta:directive
- name="defaultView"
- schema=".metadirectives.IDefaultViewDirective"
- handler="zope.app.component.metaconfigure.defaultView"
- />
-
- <meta:directive
- name="resource"
- schema=".metadirectives.IResourceDirective"
- handler="zope.app.component.metaconfigure.resource"
- />
-
- <meta:complexDirective
- name="class"
- schema=".metadirectives.IClassDirective"
- handler=".contentdirective.ClassDirective"
- >
-
- <meta:subdirective
- name="implements"
- schema=".metadirectives.IImplementsSubdirective"
- />
-
- <meta:subdirective
- name="require"
- schema=".metadirectives.IRequireSubdirective"
- />
-
- <meta:subdirective
- name="allow"
- schema=".metadirectives.IAllowSubdirective"
- />
-
- <meta:subdirective
- name="factory"
- schema=".metadirectives.IFactorySubdirective"
- />
-
- </meta:complexDirective>
-
- </meta:directives>
-
-</configure>
Deleted: Sandbox/faassen/zope.site/trunk/src/zope/site/metaconfigure.py
===================================================================
--- Sandbox/faassen/zope.site/trunk/src/zope/site/metaconfigure.py 2009-01-27 12:08:18 UTC (rev 95136)
+++ Sandbox/faassen/zope.site/trunk/src/zope/site/metaconfigure.py 2009-01-27 12:11:21 UTC (rev 95137)
@@ -1,215 +0,0 @@
-#############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""Generic Components ZCML Handlers
-
-$Id$
-"""
-__docformat__ = 'restructuredtext'
-
-import warnings
-from zope import component
-from zope.interface import Interface
-from zope.component.zcml import handler, proxify, utility
-from zope.component.interface import provideInterface
-from zope.component.interfaces import IDefaultViewName, IFactory
-from zope.configuration.exceptions import ConfigurationError
-from zope.security.checker import CheckerPublic
-from zope.security.checker import Checker, NamesChecker
-
-PublicPermission = 'zope.Public'
-
-def _checker(_context, permission, allowed_interface, allowed_attributes):
- if (not allowed_attributes) and (not allowed_interface):
- allowed_attributes = ["__call__"]
-
- if permission == PublicPermission:
- permission = CheckerPublic
-
- require={}
- if allowed_attributes:
- for name in allowed_attributes:
- require[name] = permission
- if allowed_interface:
- for i in allowed_interface:
- for name in i.names(all=True):
- require[name] = permission
-
- checker = Checker(require)
- return checker
-
-def resource(_context, factory, type, name, layer=None,
- permission=None,
- allowed_interface=None, allowed_attributes=None,
- provides=Interface):
-
- if ((allowed_attributes or allowed_interface)
- and (not permission)):
- raise ConfigurationError(
- "Must use name attribute with allowed_interface or "
- "allowed_attributes"
- )
-
- if permission:
- checker = _checker(_context, permission,
- allowed_interface, allowed_attributes)
-
- def proxyResource(request, factory=factory, checker=checker):
- return proxify(factory(request), checker)
-
- factory = proxyResource
-
- if layer is not None:
- warnings.warn_explicit(
- "The 'layer' argument of the 'resource' directive has been "
- "deprecated. Use the 'type' argument instead.",
- DeprecationWarning, _context.info.file, _context.info.line)
- type = layer
-
- _context.action(
- discriminator = ('resource', name, type, provides),
- callable = handler,
- args = ('registerAdapter',
- factory, (type,), provides, name, _context.info),
- )
- _context.action(
- discriminator = None,
- callable = provideInterface,
- args = (type.__module__ + '.' + type.__name__, type)
- )
- _context.action(
- discriminator = None,
- callable = provideInterface,
- args = (provides.__module__ + '.' + provides.__name__, type)
- )
-
-def view(_context, factory, type, name, for_, layer=None,
- permission=None, allowed_interface=None, allowed_attributes=None,
- provides=Interface):
-
- if ((allowed_attributes or allowed_interface)
- and (not permission)):
- raise ConfigurationError(
- "Must use name attribute with allowed_interface or "
- "allowed_attributes"
- )
-
- if not factory:
- raise ConfigurationError("No view factory specified.")
-
- if permission:
-
- checker = _checker(_context, permission,
- allowed_interface, allowed_attributes)
-
- class ProxyView(object):
- """Class to create simple proxy views."""
-
- def __init__(self, factory, checker):
- self.factory = factory
- self.checker = checker
-
- def __call__(self, *objects):
- return proxify(self.factory(*objects), self.checker)
-
- factory[-1] = ProxyView(factory[-1], checker)
-
-
- if not for_:
- raise ValueError("No for interfaces specified");
- for_ = tuple(for_)
-
- # Generate a single factory from multiple factories:
- factories = factory
- if len(factories) == 1:
- factory = factories[0]
- elif len(factories) < 1:
- raise ValueError("No factory specified")
- elif len(factories) > 1 and len(for_) > 1:
- raise ValueError("Can't use multiple factories and multiple for")
- else:
- def factory(ob, request):
- for f in factories[:-1]:
- ob = f(ob)
- return factories[-1](ob, request)
-
- # BBB 2006/02/18, to be removed after 12 months
- if layer is not None:
- for_ = for_ + (layer,)
- warnings.warn_explicit(
- "The 'layer' argument of the 'view' directive has been "
- "deprecated. Use the 'type' argument instead. If you have "
- "an existing 'type' argument IBrowserRequest, replace it with the "
- "'layer' argument (the layer subclasses IBrowserRequest). "
- "which subclasses BrowserRequest.",
- DeprecationWarning, _context.info.file, _context.info.line)
- else:
- for_ = for_ + (type,)
-
- _context.action(
- discriminator = ('view', for_, name, provides),
- callable = handler,
- args = ('registerAdapter',
- factory, for_, provides, name, _context.info),
- )
- if type is not None:
- _context.action(
- discriminator = None,
- callable = provideInterface,
- args = ('', type)
- )
-
- _context.action(
- discriminator = None,
- callable = provideInterface,
- args = ('', provides)
- )
-
- if for_ is not None:
- for iface in for_:
- if iface is not None:
- _context.action(
- discriminator = None,
- callable = provideInterface,
- args = ('', iface)
- )
-############################################################################
-# BBB: Deprecated. Will go away in 3.3.
-
-def defaultView(_context, type, name, for_):
-
- _context.action(
- discriminator = ('defaultViewName', for_, type, name),
- callable = handler,
- args = ('registerAdapter',
- name, (for_, type), IDefaultViewName, '',_context.info)
- )
-
- _context.action(
- discriminator = None,
- callable = provideInterface,
- args = ('', type)
- )
-
- _context.action(
- discriminator = None,
- callable = provideInterface,
- args = ('', for_)
- )
-
-from zope.deprecation import deprecated
-deprecated('defaultView',
- 'The zope:defaultView directive has been deprecated in favor of '
- 'the browser:defaultView directive. '
- 'Will be gone in Zope 3.3.')
-
Deleted: Sandbox/faassen/zope.site/trunk/src/zope/site/metadirectives.py
===================================================================
--- Sandbox/faassen/zope.site/trunk/src/zope/site/metadirectives.py 2009-01-27 12:08:18 UTC (rev 95136)
+++ Sandbox/faassen/zope.site/trunk/src/zope/site/metadirectives.py 2009-01-27 12:11:21 UTC (rev 95137)
@@ -1,297 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""Component architecture related 'zope' ZCML namespace directive interfaces
-
-$Id$
-"""
-__docformat__ = 'restructuredtext'
-
-import zope.configuration.fields
-import zope.security.zcml
-import zope.interface
-import zope.schema
-from zope.component.zcml import IBasicComponentInformation
-
-from zope.app.component.i18n import ZopeMessageFactory as _
-
-class IDefaultViewName(zope.interface.Interface):
- """A string that contains the default view name
-
- A default view name is used to select a view when a user hasn't
- specified one.
- """
-
-class IBasicViewInformation(zope.interface.Interface):
- """This is the basic information for all views."""
-
- for_ = zope.configuration.fields.Tokens(
- title=_("Specifications of the objects to be viewed"),
- description=_("""This should be a list of interfaces or classes
- """),
- required=True,
- value_type=zope.configuration.fields.GlobalObject(
- missing_value=object(),
- ),
- )
-
- permission = zope.security.zcml.Permission(
- title=_("Permission"),
- description=_("The permission needed to use the view."),
- required=False,
- )
-
- class_ = zope.configuration.fields.GlobalObject(
- title=_("Class"),
- description=_("A class that provides attributes used by the view."),
- required=False,
- )
-
- layer = zope.configuration.fields.GlobalInterface(
- title=_("The layer the view is in."),
- description=_("""
- A skin is composed of layers. It is common to put skin
- specific views in a layer named after the skin. If the 'layer'
- attribute is not supplied, it defaults to 'default'."""),
- required=False,
- )
-
- allowed_interface = zope.configuration.fields.Tokens(
- title=_("Interface that is also allowed if user has permission."),
- description=_("""
- By default, 'permission' only applies to viewing the view and
- any possible sub views. By specifying this attribute, you can
- make the permission also apply to everything described in the
- supplied interface.
-
- Multiple interfaces can be provided, separated by
- whitespace."""),
- required=False,
- value_type=zope.configuration.fields.GlobalInterface(),
- )
-
- allowed_attributes = zope.configuration.fields.Tokens(
- title=_("View attributes that are also allowed if the user"
- " has permission."),
- description=_("""
- By default, 'permission' only applies to viewing the view and
- any possible sub views. By specifying 'allowed_attributes',
- you can make the permission also apply to the extra attributes
- on the view object."""),
- required=False,
- value_type=zope.configuration.fields.PythonIdentifier(),
- )
-
-class IBasicResourceInformation(zope.interface.Interface):
- """
- Basic information for resources
- """
-
- name = zope.schema.TextLine(
- title=_("The name of the resource."),
- description=_("The name shows up in URLs/paths. For example 'foo'."),
- required=True,
- default=u'',
- )
-
- provides = zope.configuration.fields.GlobalInterface(
- title=_("The interface this component provides."),
- description=_("""
- A view can provide an interface. This would be used for
- views that support other views."""),
- required=False,
- default=zope.interface.Interface,
- )
-
- type = zope.configuration.fields.GlobalInterface(
- title=_("Request type"),
- required=True
- )
-
-
-class IViewDirective(IBasicViewInformation, IBasicResourceInformation):
- """Register a view for a component"""
-
- factory = zope.configuration.fields.Tokens(
- title=_("Factory"),
- required=False,
- value_type=zope.configuration.fields.GlobalObject(),
- )
-
-############################################################################
-# BBB: Deprecated; use browser:defaultView instead. Will go away in 3.3.
-class IDefaultViewDirective(IBasicResourceInformation):
- """
- *BBB: DEPRECATED*
-
- Use ``browser:defaultView`` instead.
-
- The name of the view that should be the default.
-
- This name refers to view that should be the
- view used by default (if no view name is supplied
- explicitly).
- """
-
- for_ = zope.configuration.fields.GlobalInterface(
- title=_("The interface this view is the default for."),
- description=_("""
- Specifies the interface for which the default view is declared. All
- objects implementing this interface make use of this default
- setting. If this attribute is not specified, the default is available
- for all objects."""),
- required=False,
- )
-############################################################################
-
-
-class IResourceDirective(IBasicComponentInformation,
- IBasicResourceInformation):
- """Register a resource"""
-
- layer = zope.configuration.fields.GlobalInterface(
- title=_("The layer the resource is in."),
- required=False,
- )
-
- allowed_interface = zope.configuration.fields.Tokens(
- title=_("Interface that is also allowed if user has permission."),
- required=False,
- value_type=zope.configuration.fields.GlobalInterface(),
- )
-
- allowed_attributes = zope.configuration.fields.Tokens(
- title=_("View attributes that are also allowed if user"
- " has permission."),
- required=False,
- value_type=zope.configuration.fields.PythonIdentifier(),
- )
-
-
-class IClassDirective(zope.interface.Interface):
- """Make statements about a class"""
-
- class_ = zope.configuration.fields.GlobalObject(
- title=_("Class"),
- required=True
- )
-
-class IImplementsSubdirective(zope.interface.Interface):
- """Declare that the class given by the content directive's class
- attribute implements a given interface
- """
-
- interface = zope.configuration.fields.Tokens(
- title=_("One or more interfaces"),
- required=True,
- value_type=zope.configuration.fields.GlobalInterface()
- )
-
-class IRequireSubdirective(zope.interface.Interface):
- """Indicate that the a specified list of names or the names in a
- given Interface require a given permission for access.
- """
-
- permission = zope.security.zcml.Permission(
- title=_("Permission"),
- description=_("""
- Specifies the permission by id that will be required to
- access or mutate the attributes and methods specified."""),
- required=False,
- )
-
- attributes = zope.configuration.fields.Tokens(
- title=_("Attributes and methods"),
- description=_("This is a list of attributes and methods"
- " that can be accessed."),
- required=False,
- value_type=zope.configuration.fields.PythonIdentifier(),
- )
-
- set_attributes = zope.configuration.fields.Tokens(
- title=_("Attributes that can be set"),
- description=_("This is a list of attributes that can be"
- " modified/mutated."),
- required=False,
- value_type=zope.configuration.fields.PythonIdentifier(),
- )
-
- interface = zope.configuration.fields.Tokens(
- title=_("Interfaces"),
- description=_("The listed interfaces' methods and attributes"
- " can be accessed."),
- required=False,
- value_type=zope.configuration.fields.GlobalInterface(),
- )
-
- set_schema = zope.configuration.fields.Tokens(
- title=_("The attributes specified by the schema can be set"),
- description=_("The listed schemas' properties can be"
- " modified/mutated."),
- required=False,
- value_type=zope.configuration.fields.GlobalInterface(),
- )
-
- like_class = zope.configuration.fields.GlobalObject(
- title=_("Configure like this class"),
- description=_("""
- This argument says that this content class should be configured in the
- same way the specified class' security is. If this argument is
- specified, no other argument can be used."""),
- required=False,
- )
-
-class IAllowSubdirective(zope.interface.Interface):
- """
- Declare a part of the class to be publicly viewable (that is,
- requires the zope.Public permission). Only one of the following
- two attributes may be used.
- """
-
- attributes = zope.configuration.fields.Tokens(
- title=_("Attributes"),
- required=False,
- value_type=zope.configuration.fields.PythonIdentifier(),
- )
-
- interface = zope.configuration.fields.Tokens(
- title=_("Interface"),
- required=False,
- value_type=zope.configuration.fields.GlobalInterface(),
- )
-
-class IFactorySubdirective(zope.interface.Interface):
- """Specify the factory used to create this content object"""
-
- id = zope.schema.Id(
- title=_("ID"),
- description=_("""
- the identifier for this factory in the ZMI factory
- identification scheme. If not given, defaults to the literal
- string given as the content directive's 'class' attribute."""),
- required=False,
- )
-
- title = zope.configuration.fields.MessageID(
- title=_("Title"),
- description=_("Text suitable for use in the 'add content' menu"
- " of a management interface"),
- required=False,
- )
-
- description = zope.configuration.fields.MessageID(
- title=_("Description"),
- description=_("Longer narrative description of what this"
- " factory does"),
- required=False,
- )
Deleted: Sandbox/faassen/zope.site/trunk/src/zope/site/vocabulary.py
===================================================================
--- Sandbox/faassen/zope.site/trunk/src/zope/site/vocabulary.py 2009-01-27 12:08:18 UTC (rev 95136)
+++ Sandbox/faassen/zope.site/trunk/src/zope/site/vocabulary.py 2009-01-27 12:11:21 UTC (rev 95137)
@@ -1,387 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2004 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""Utility Vocabulary.
-
-This vocabulary provides terms for all utilities providing a given interface.
-
-$Id$
-"""
-__docformat__ = "reStructuredText"
-
-import zope.component
-from zope.interface import implements, classProvides, Interface
-from zope.interface.interfaces import IInterface
-from zope.schema.interfaces import IVocabularyTokenized
-from zope.schema.interfaces import ITokenizedTerm, ITitledTokenizedTerm
-from zope.schema.interfaces import IVocabularyFactory
-
-from zope.app.component.i18n import ZopeMessageFactory as _
-from zope.app.interface.vocabulary import ObjectInterfacesVocabulary
-from zope.component.interfaces import IUtilityRegistration
-
-class UtilityTerm(object):
- """A term representing a utility.
-
- The token of the term is the name of the utility. Here is a brief example
- on how the IVocabulary interface is handled in this term as a
- utility:
-
- >>> from zope.interface.verify import verifyObject
- >>> from zope.schema.interfaces import IVocabulary
- >>> term = UtilityTerm(IVocabulary, 'zope.schema.interfaces.IVocabulary')
- >>> verifyObject(ITokenizedTerm, term)
- True
-
- >>> term.value
- <InterfaceClass zope.schema.interfaces.IVocabulary>
- >>> term.token
- 'zope.schema.interfaces.IVocabulary'
-
- >>> term
- <UtilityTerm zope.schema.interfaces.IVocabulary, instance of InterfaceClass>
- """
- implements(ITokenizedTerm)
-
- def __init__(self, value, token):
- """Create a term for value and token."""
- self.value = value
- self.token = token
-
- def __repr__(self):
- return '<UtilityTerm %s, instance of %s>' %(
- self.token, self.value.__class__.__name__)
-
-
-class UtilityVocabulary(object):
- """Vocabulary that provides utilities of a specified interface.
-
- Here is a short example of how the vocabulary should work.
-
- First we need to create a utility interface and some utilities:
-
- >>> class IObject(Interface):
- ... 'Simple interface to mark object utilities.'
- >>>
- >>> class Object(object):
- ... implements(IObject)
- ... def __init__(self, name):
- ... self.name = name
- ... def __repr__(self):
- ... return '<Object %s>' %self.name
-
- Now we register some utilities for IObject
-
- >>> from zope.app.testing import ztapi
- >>> object1 = Object('object1')
- >>> ztapi.provideUtility(IObject, object1, 'object1')
- >>> object2 = Object('object2')
- >>> ztapi.provideUtility(IObject, object2, 'object2')
- >>> object3 = Object('object3')
- >>> ztapi.provideUtility(IObject, object3, 'object3')
- >>> object4 = Object('object4')
-
- We are now ready to create a vocabulary that we can use; in our case
- everything is global, so the context is None.
-
- >>> vocab = UtilityVocabulary(None, interface=IObject)
- >>> import pprint
- >>> pprint.pprint(vocab._terms.items())
- [(u'object1', <UtilityTerm object1, instance of Object>),
- (u'object2', <UtilityTerm object2, instance of Object>),
- (u'object3', <UtilityTerm object3, instance of Object>)]
-
- Now let's see how the other methods behave in this context. First we can
- just use the 'in' opreator to test whether a value is available.
-
- >>> object1 in vocab
- True
- >>> object4 in vocab
- False
-
- We can also create a lazy iterator. Note that the utility terms might
- appear in a different order than the utilities were registered.
-
- >>> iterator = iter(vocab)
- >>> terms = list(iterator)
- >>> names = [term.token for term in terms]
- >>> names.sort()
- >>> names
- [u'object1', u'object2', u'object3']
-
- Determining the amount of utilities available via the vocabulary is also
- possible.
-
- >>> len(vocab)
- 3
-
- Next we are looking at some of the more vocabulary-characteristic API
- methods.
-
- One can get a term for a given value using ``getTerm()``:
-
- >>> vocab.getTerm(object1)
- <UtilityTerm object1, instance of Object>
- >>> vocab.getTerm(object4)
- Traceback (most recent call last):
- ...
- LookupError: <Object object4>
-
- On the other hand, if you want to get a term by the token, then you do
- that with:
-
- >>> vocab.getTermByToken('object1')
- <UtilityTerm object1, instance of Object>
- >>> vocab.getTermByToken('object4')
- Traceback (most recent call last):
- ...
- LookupError: object4
-
- That's it. It is all pretty straight forward, but it allows us to easily
- create a vocabulary for any utility. In fact, to make it easy to register
- such a vocabulary via ZCML, the `interface` argument to the constructor
- can be a string that is resolved via the utility registry. The ZCML looks
- like this:
-
- <zope:vocabulary
- name='IObjects'
- factory='zope.app.utility.vocabulary.UtilityVocabulary'
- interface='zope.app.utility.vocabulary.IObject' />
-
- >>> ztapi.provideUtility(IInterface, IObject,
- ... 'zope.app.utility.vocabulary.IObject')
- >>> vocab = UtilityVocabulary(
- ... None, interface='zope.app.utility.vocabulary.IObject')
- >>> pprint.pprint(vocab._terms.items())
- [(u'object1', <UtilityTerm object1, instance of Object>),
- (u'object2', <UtilityTerm object2, instance of Object>),
- (u'object3', <UtilityTerm object3, instance of Object>)]
-
- Sometimes it is desirable to only select the name of a utility. For
- this purpose a `nameOnly` argument was added to the constructor, in which
- case the UtilityTerm's value is not the utility itself but the name of the
- utility.
-
- >>> vocab = UtilityVocabulary(None, interface=IObject, nameOnly=True)
- >>> pprint.pprint([term.value for term in vocab])
- [u'object1', u'object2', u'object3']
- """
- implements(IVocabularyTokenized)
- classProvides(IVocabularyFactory)
-
- # override these in subclasses
- interface = Interface
- nameOnly = False
-
- def __init__(self, context, **kw):
- if kw:
- # BBB 2006/02/24, to be removed after 12 months
- # the 'interface' and 'nameOnly' parameters are supposed to be
- # set as class-level attributes in custom subclasses now.
- self.nameOnly = bool(kw.get('nameOnly', False))
- interface = kw.get('interface', Interface)
- if isinstance(interface, (str, unicode)):
- interface = zope.component.getUtility(IInterface, interface)
- self.interface = interface
-
- utils = zope.component.getUtilitiesFor(self.interface, context)
- self._terms = dict(
- (name, UtilityTerm(self.nameOnly and name or util, name))
- for name, util in utils)
-
- def __contains__(self, value):
- """See zope.schema.interfaces.IBaseVocabulary"""
- return value in (term.value for term in self._terms.values())
-
- def getTerm(self, value):
- """See zope.schema.interfaces.IBaseVocabulary"""
- try:
- return [term for name, term in self._terms.items()
- if term.value == value][0]
- except IndexError:
- raise LookupError(value)
-
- def getTermByToken(self, token):
- """See zope.schema.interfaces.IVocabularyTokenized"""
- try:
- return self._terms[token]
- except KeyError:
- raise LookupError(token)
-
- def __iter__(self):
- """See zope.schema.interfaces.IIterableVocabulary"""
- # Sort the terms by the token (utility name)
- values = self._terms.values()
- values.sort(lambda x, y: cmp(x.token, y.token))
- return iter(values)
-
- def __len__(self):
- """See zope.schema.interfaces.IIterableVocabulary"""
- return len(self._terms)
-
-class InterfacesVocabulary(UtilityVocabulary):
- classProvides(IVocabularyFactory)
- interface = IInterface
-
-
-class UtilityComponentInterfacesVocabulary(ObjectInterfacesVocabulary):
- classProvides(IVocabularyFactory)
-
- def __init__(self, context):
- if IUtilityRegistration.providedBy(context):
- context = context.component
- super(UtilityComponentInterfacesVocabulary, self).__init__(
- context)
-
-
-class UtilityNameTerm:
- r"""Simple term that provides a utility name as a value.
-
- >>> t1 = UtilityNameTerm('abc')
- >>> t2 = UtilityNameTerm(u'\xC0\xDF\xC7')
- >>> t1.value
- u'abc'
- >>> t2.value
- u'\xc0\xdf\xc7'
- >>> t1.title
- u'abc'
- >>> repr(t2.title)
- "u'\\xc0\\xdf\\xc7'"
- >>> ITitledTokenizedTerm.providedBy(t1)
- True
-
- The tokens used for form values are Base-64 encodings of the
- names, with the letter 't' prepended to ensure the unnamed utility
- is supported:
-
- >>> t1.token
- 'tYWJj'
- >>> t2.token
- 'tw4DDn8OH'
-
- The unnamed utility is given an artificial title for use in user
- interfaces:
-
- >>> t3 = UtilityNameTerm(u'')
- >>> t3.title
- u'(unnamed utility)'
-
- """
-
- implements(ITitledTokenizedTerm)
-
- def __init__(self, value):
- self.value = unicode(value)
-
- @property
- def token(self):
- # Return our value as a token. This is required to be 7-bit
- # printable ascii. We'll use base64 generated from the UTF-8
- # representation. (The default encoding rules should not be
- # allowed to apply.)
- return "t" + self.value.encode('utf-8').encode('base64')[:-1]
-
- @property
- def title(self):
- return self.value or _("(unnamed utility)")
-
-
-class UtilityNames:
- """Vocabulary with utility names for a single interface as values.
-
- >>> class IMyUtility(Interface):
- ... pass
-
- >>> class MyUtility(object):
- ... implements(IMyUtility)
-
- >>> vocab = UtilityNames(IMyUtility)
-
- >>> from zope.schema.interfaces import IVocabulary
- >>> IVocabulary.providedBy(vocab)
- True
- >>> IVocabularyTokenized.providedBy(vocab)
- True
-
- >>> from zope.app.testing import placelesssetup
- >>> from zope.app.testing import ztapi
- >>> placelesssetup.setUp()
-
- >>> ztapi.provideUtility(IMyUtility, MyUtility(), 'one')
- >>> ztapi.provideUtility(IMyUtility, MyUtility(), 'two')
-
- >>> unames = UtilityNames(IMyUtility)
- >>> len(list(unames))
- 2
- >>> L = [t.value for t in unames]
- >>> L.sort()
- >>> L
- [u'one', u'two']
-
- >>> u'one' in vocab
- True
- >>> u'three' in vocab
- False
- >>> ztapi.provideUtility(IMyUtility, MyUtility(), 'three')
- >>> u'three' in vocab
- True
-
- >>> ztapi.provideUtility(IMyUtility, MyUtility())
- >>> u'' in vocab
- True
- >>> term1 = vocab.getTerm(u'')
- >>> term2 = vocab.getTermByToken(term1.token)
- >>> term2.value
- u''
- >>> term3 = vocab.getTerm(u'one')
- >>> term3.token
- 'tb25l'
- >>> term3a = vocab.getTermByToken('tb25l')
- >>> term3.value
- u'one'
-
- >>> placelesssetup.tearDown()
- """
-
- implements(IVocabularyTokenized)
-
- def __init__(self, interface):
- self.interface = interface
-
- def __contains__(self, value):
- return zope.component.queryUtility(self.interface, value) is not None
-
- def getTerm(self, value):
- if value in self:
- return UtilityNameTerm(value)
- raise ValueError(value)
-
- def getTermByToken(self, token):
- for name, ut in zope.component.getUtilitiesFor(self.interface):
- name = unicode(name)
- if token == "t":
- if not name:
- break
- elif UtilityNameTerm(name).token == token:
- break
- else:
- raise LookupError("no matching token: %r" % token)
- return self.getTerm(name)
-
- def __iter__(self):
- for name, ut in zope.component.getUtilitiesFor(self.interface):
- yield UtilityNameTerm(name)
-
- def __len__(self):
- """Return the number of valid terms, or sys.maxint."""
- return len(list(zope.component.getUtilitiesFor(self.interface)))
More information about the Checkins
mailing list