Beispiel #1
0
class IReservedNames(Interface):
    """A sequence of names that are reserved for that container"""

    reservedNames = Set(
        title=_(u'Reserved Names'),
        description=_(u'Names that are not allowed for addable content'),
        required=True,
    )
Beispiel #2
0
    def action(self, type_name='', id=''):
        if not type_name:
            raise UserError(_(u"You must select the type of object to add."))

        if type_name.startswith('@@'):
            type_name = type_name[2:]

        if '/' in type_name:
            view_name = type_name.split('/', 1)[0]
        else:
            view_name = type_name

        if queryMultiAdapter((self, self.request), name=view_name) is not None:
            url = "%s/%s=%s" % (absoluteURL(self, self.request), type_name, id)
            self.request.response.redirect(url)
            return

        if not self.contentName:
            self.contentName = id

        factory = getUtility(IFactory, type_name)
        content = factory()

        notify(ObjectCreatedEvent(content))

        self.add(content)
        self.request.response.redirect(self.nextURL())
Beispiel #3
0
    def action(self, type_name='', id=''):
        if not type_name:
            raise UserError(_(u"You must select the type of object to add."))

        if type_name.startswith('@@'):
            type_name = type_name[2:]

        if '/' in type_name:
            view_name = type_name.split('/', 1)[0]
        else:
            view_name = type_name

        if queryMultiAdapter((self, self.request),
                             name=view_name) is not None:
            url = "%s/%s=%s" % (
                absoluteURL(self, self.request), type_name, id)
            self.request.response.redirect(url)
            return

        if not self.contentName:
            self.contentName = id

        factory = getUtility(IFactory, type_name)
        content = factory()

        notify(ObjectCreatedEvent(content))

        self.add(content)
        self.request.response.redirect(self.nextURL())
Beispiel #4
0
def checkObject(container, name, object):
    """Check containement constraints for an object and container
    """

    # check __setitem__ precondition
    containerProvided = providedBy(container)
    __setitem__ = containerProvided.get('__setitem__')
    if __setitem__ is not None:
        precondition = __setitem__.queryTaggedValue('precondition')
        if precondition is not None:
            precondition(container, name, object)

    # check the constraint on __parent__
    __parent__ = providedBy(object).get('__parent__')
    if __parent__ is not None:
        try:
            validate = __parent__.validate
        except AttributeError:
            pass
        else:
            validate(container)


    if not containerProvided.extends(IContainer):
        # If it doesn't implement IContainer, it can't contain stuff.
        raise TypeError(
            _('Container is not a valid Zope container.')
            )
Beispiel #5
0
def checkObject(container, name, object):
    """Check containment constraints for an object and container
    """

    # check __setitem__ precondition
    containerProvided = providedBy(container)
    __setitem__ = containerProvided.get('__setitem__')
    if __setitem__ is not None:
        precondition = __setitem__.queryTaggedValue('precondition')
        if precondition is not None:
            precondition(container, name, object)

    # check that object is not being pasted into itself or its children.
    target = container
    while target is not None:
        if target is object:
            raise TypeError("Cannot add an object to itself or its children.")
        if zope.location.interfaces.ILocation.providedBy(target):
            target = target.__parent__
        else:
            target = None

    # check the constraint on __parent__
    __parent__ = providedBy(object).get('__parent__')
    if __parent__ is not None:
        try:
            validate = __parent__.validate
        except AttributeError:
            pass
        else:
            validate(container)

    if not containerProvided.extends(IContainer):
        # If it doesn't implement IContainer, it can't contain stuff.
        raise TypeError(_('Container is not a valid Zope container.'))
Beispiel #6
0
def checkObject(container, name, object):
    """Check containment constraints for an object and container
    """

    # check __setitem__ precondition
    containerProvided = providedBy(container)
    __setitem__ = containerProvided.get('__setitem__')
    if __setitem__ is not None:
        precondition = __setitem__.queryTaggedValue('precondition')
        if precondition is not None:
            precondition(container, name, object)

    # check that object is not being pasted into itself or its children.
    target = container
    while target is not None:
        if target is object:
            raise TypeError("Cannot add an object to itself or its children.")
        if zope.location.interfaces.ILocation.providedBy(target):
            target = target.__parent__
        else:
            target = None

    # check the constraint on __parent__
    __parent__ = providedBy(object).get('__parent__')
    if __parent__ is not None:
        try:
            validate = __parent__.validate
        except AttributeError:
            pass
        else:
            validate(container)


    if not containerProvided.extends(IContainer):
        # If it doesn't implement IContainer, it can't contain stuff.
        raise TypeError(
            _('Container is not a valid Zope container.')
            )
Beispiel #7
0
 def sizeForDisplay(self):
     """See `ISized`"""
     num_items = len(self._container)
     if num_items == 1:
         return _('1 item')
     return _('${items} items', mapping={'items': str(num_items)})
Beispiel #8
0
    def checkName(self, name, object):  # pylint:disable=redefined-builtin
        """See zope.container.interfaces.INameChooser

        We create and populate a dummy container

        >>> from zope.container.sample import SampleContainer
        >>> container = SampleContainer()
        >>> container['foo'] = 'bar'
        >>> from zope.container.contained import NameChooser

        An invalid name raises a ValueError:

        >>> NameChooser(container).checkName('+foo', object())
        Traceback (most recent call last):
        ...
        ValueError: Names cannot begin with '+' or '@' or contain '/'

        A name that already exists raises a KeyError:

        >>> NameChooser(container).checkName('foo', object())
        Traceback (most recent call last):
        ...
        KeyError: u'The given name is already being used'

        A name must be a string or unicode string:

        >>> NameChooser(container).checkName(2, object())
        Traceback (most recent call last):
        ...
        TypeError: ('Invalid name type', <type 'int'>)

        A correct name returns True:

        >>> NameChooser(container).checkName('2', object())
        True

        We can reserve some names by providing a IReservedNames adapter
        to a container:

        >>> from zope.container.interfaces import IContainer
        >>> @zope.component.adapter(IContainer)
        ... @zope.interface.implementer(IReservedNames)
        ... class ReservedNames(object):
        ...
        ...     def __init__(self, context):
        ...         self.reservedNames = set(('reserved', 'other'))

        >>> zope.component.getSiteManager().registerAdapter(ReservedNames)

        >>> NameChooser(container).checkName('reserved', None)
        Traceback (most recent call last):
        ...
        NameReserved: reserved
        """

        if isinstance(name, bytes):
            name = name.decode('ascii')
        elif not isinstance(name, text_type):
            raise TypeError("Invalid name type", type(name))

        if not name:
            raise ValueError(
                _("An empty name was provided. Names cannot be empty."))

        if name[:1] in '+@' or '/' in name:
            raise ValueError(
                _("Names cannot begin with '+' or '@' or contain '/'"))

        reserved = IReservedNames(self.context, None)
        if reserved is not None:
            if name in reserved.reservedNames:
                raise NameReserved(name)

        if name in self.context:
            raise KeyError(_("The given name is already being used"))

        return True
Beispiel #9
0
    def checkName(self, name, object):
        """See zope.container.interfaces.INameChooser

        We create and populate a dummy container

        >>> from zope.container.sample import SampleContainer
        >>> container = SampleContainer()
        >>> container['foo'] = 'bar'
        >>> from zope.container.contained import NameChooser

        An invalid name raises a ValueError:

        >>> NameChooser(container).checkName('+foo', object())
        Traceback (most recent call last):
        ...
        ValueError: Names cannot begin with '+' or '@' or contain '/'

        A name that already exists raises a KeyError:

        >>> NameChooser(container).checkName('foo', object())
        Traceback (most recent call last):
        ...
        KeyError: u'The given name is already being used'

        A name must be a string or unicode string:

        >>> NameChooser(container).checkName(2, object())
        Traceback (most recent call last):
        ...
        TypeError: ('Invalid name type', <type 'int'>)

        A correct name returns True:

        >>> NameChooser(container).checkName('2', object())
        True

        We can reserve some names by providing a IReservedNames adapter
        to a container:

        >>> from zope.container.interfaces import IContainer
        >>> @zope.component.adapter(IContainer)
        ... @zope.interface.implementer(IReservedNames)
        ... class ReservedNames(object):
        ...
        ...     def __init__(self, context):
        ...         self.reservedNames = set(('reserved', 'other'))

        >>> zope.component.getSiteManager().registerAdapter(ReservedNames)

        >>> NameChooser(container).checkName('reserved', None)
        Traceback (most recent call last):
        ...
        NameReserved: reserved
        """

        if isinstance(name, bytes):
            name = name.decode('ascii')
        elif not isinstance(name, text_type):
            raise TypeError("Invalid name type", type(name))

        if not name:
            raise ValueError(
                _("An empty name was provided. Names cannot be empty.")
                )

        if name[:1] in '+@' or '/' in name:
            raise ValueError(
                _("Names cannot begin with '+' or '@' or contain '/'")
                )

        reserved = IReservedNames(self.context, None)
        if reserved is not None:
            if name in reserved.reservedNames:
                raise NameReserved(name)

        if name in self.context:
            raise KeyError(
                _("The given name is already being used")
                )

        return True
Beispiel #10
0
class NameReserved(ValueError):
    __doc__ = _("""The name is reserved for this container""")
Beispiel #11
0
 def sizeForDisplay(self):
     """See `ISized`"""
     num_items = len(self._container)
     if num_items == 1:
         return _('1 item')
     return _('${items} items', mapping={'items': str(num_items)})
Beispiel #12
0
    def checkName(self, name, object):
        """See zope.container.interfaces.INameChooser

        We create and populate a dummy container

        >>> from zope.container.sample import SampleContainer
        >>> container = SampleContainer()
        >>> container['foo'] = 'bar'
        >>> from zope.container.contained import NameChooser

        All these names are invalid:

        >>> NameChooser(container).checkName('+foo', object())
        Traceback (most recent call last):
        ...
        ValueError: Names cannot begin with '+' or '@' or contain '/'
        >>> NameChooser(container).checkName('@foo', object())
        Traceback (most recent call last):
        ...
        ValueError: Names cannot begin with '+' or '@' or contain '/'
        >>> NameChooser(container).checkName('f/oo', object())
        Traceback (most recent call last):
        ...
        ValueError: Names cannot begin with '+' or '@' or contain '/'
        >>> NameChooser(container).checkName('foo', object())
        Traceback (most recent call last):
        ...
        KeyError: u'The given name is already being used'
        >>> NameChooser(container).checkName(2, object())
        Traceback (most recent call last):
        ...
        TypeError: ('Invalid name type', <type 'int'>)

        This one is ok:

        >>> NameChooser(container).checkName('2', object())
        True

        We can reserve some names by providing a IReservedNames adapter
        to a container:
        
        >>> NameChooser(container).checkName('reserved', None)
        True
        >>> NameChooser(container).checkName('other', None)
        True

        >>> from zope.container.interfaces import IContainer
        >>> class ReservedNames(object):
        ...     zope.component.adapts(IContainer)
        ...     zope.interface.implements(IReservedNames)
        ...
        ...     def __init__(self, context):
        ...         self.reservedNames = set(('reserved', 'other'))

        >>> zope.component.provideAdapter(ReservedNames)

        >>> NameChooser(container).checkName('reserved', None)
        Traceback (most recent call last):
        ...
        NameReserved: reserved
        >>> NameChooser(container).checkName('other', None)
        Traceback (most recent call last):
        ...
        NameReserved: other

        """

        if not name:
            raise ValueError(
                _("An empty name was provided. Names cannot be empty.")
                )

        if isinstance(name, str):
            name = unicode(name)
        elif not isinstance(name, unicode):
            raise TypeError("Invalid name type", type(name))

        if name[:1] in '+@' or '/' in name:
            raise ValueError(
                _("Names cannot begin with '+' or '@' or contain '/'")
                )

        reserved = IReservedNames(self.context, None)
        if reserved is not None:
            if name in reserved.reservedNames:
                raise NameReserved(name)

        if name in self.context:
            raise KeyError(
                _("The given name is already being used")
                )

        return True