PK4~7zope/__init__.py# namespace package boilerplate try: __import__('pkg_resources').declare_namespace(__name__) except ImportError, e: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) PK4G‰zope/__init__.pyc; 43Dc@sOyedieWn1ej o%ZdklZeeeZnXdS(s pkg_resources(s extend_pathN(s __import__sdeclare_namespaces__name__s ImportErrorsespkgutils extend_paths__path__(ses extend_paths__path__((s+build/bdist.linux-i686/egg/zope/__init__.pys?s PKl4W,,zope/schema/_bootstrapfields.py############################################################################## # # Copyright (c) 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. # ############################################################################## """Bootstrapping fields $Id: _bootstrapfields.py 27082 2004-08-12 20:03:58Z srichter $ """ from zope.interface import Attribute, providedBy, implements from zope.schema._bootstrapinterfaces import StopValidation from zope.schema._bootstrapinterfaces import IFromUnicode from zope.schema._bootstrapinterfaces import RequiredMissing, WrongType from zope.schema._bootstrapinterfaces import ConstraintNotSatisfied from zope.schema._bootstrapinterfaces import NotAContainer, NotAnIterator from zope.schema._bootstrapinterfaces import TooSmall, TooBig from zope.schema._bootstrapinterfaces import TooShort, TooLong from zope.schema._bootstrapinterfaces import InvalidValue from zope.schema._schema import getFields class ValidatedProperty(object): def __init__(self, name, check=None): self._info = name, check def __set__(self, inst, value): name, check = self._info if value is not None: if check is not None: check(inst, value) else: inst.validate(value) inst.__dict__[name] = value class Field(Attribute): # Type restrictions, if any _type = None context = None # If a field has no assigned value, it will be set to missing_value. missing_value = None # This is the default value for the missing_value argument to the # Field constructor. A marker is helpful since we don't want to # overwrite missing_value if it is set differently on a Field # subclass and isn't specified via the constructor. __missing_value_marker = object() # Note that the "order" field has a dual existance: # 1. The class variable Field.order is used as a source for the # monotonically increasing values used to provide... # 2. The instance variable self.order which provides a # monotonically increasing value that tracks the creation order # of Field (including Field subclass) instances. order = 0 constraint = None default = ValidatedProperty('default') def __init__(self, title=u'', description=u'', __name__='', required=True, readonly=False, constraint=None, default=None, missing_value=__missing_value_marker): """Pass in field values as keyword parameters. Generally, you want to pass either a title and description, or a doc string. If you pass no doc string, it will be computed from the title and description. If you pass a doc string that follows the Python coding style (title line separated from the body by a blank line), the title and description will be computed from the doc string. Unfortunately, the doc string must be passed as a positional argument. Here are some examples: >>> f = Field() >>> f.__doc__, f.title, f.description ('', u'', u'') >>> f = Field(title=u'sample') >>> f.__doc__, f.title, f.description (u'sample', u'sample', u'') >>> f = Field(title=u'sample', description=u'blah blah\\nblah') >>> f.__doc__, f.title, f.description (u'sample\\n\\nblah blah\\nblah', u'sample', u'blah blah\\nblah') """ __doc__ = '' if title: if description: __doc__ = "%s\n\n%s" % (title, description) else: __doc__ = title elif description: __doc__ = description super(Field, self).__init__(__name__, __doc__) self.title = title self.description = description self.required = required self.readonly = readonly if constraint is not None: self.constraint = constraint self.default = default # Keep track of the order of field definitions Field.order += 1 self.order = Field.order if missing_value is not self.__missing_value_marker: self.missing_value = missing_value def bind(self, object): clone = self.__class__.__new__(self.__class__) clone.__dict__.update(self.__dict__) clone.context = object return clone def validate(self, value): if value == self.missing_value: if self.required: raise RequiredMissing else: try: self._validate(value) except StopValidation: pass def __eq__(self, other): # should be the same type if type(self) != type(other): return False # should have the same properties names = {} # used as set of property names, ignoring values for interface in providedBy(self): names.update(getFields(interface)) # order will be different always, don't compare it if 'order' in names: del names['order'] for name in names: if getattr(self, name) != getattr(other, name): return False return True def __ne__(self, other): return not self.__eq__(other) def _validate(self, value): if self._type is not None and not isinstance(value, self._type): raise WrongType(value, self._type) if self.constraint is not None and not self.constraint(value): raise ConstraintNotSatisfied(value) def get(self, object): return getattr(object, self.__name__) def query(self, object, default=None): return getattr(object, self.__name__, default) def set(self, object, value): if self.readonly: raise TypeError("Can't set values on read-only fields " "(name=%s, class=%s.%s)" % (self.__name__, object.__class__.__module__, object.__class__.__name__)) setattr(object, self.__name__, value) class Container(Field): def _validate(self, value): super(Container, self)._validate(value) if not hasattr(value, '__contains__'): try: iter(value) except TypeError: raise NotAContainer(value) class Iterable(Container): def _validate(self, value): super(Iterable, self)._validate(value) # See if we can get an iterator for it try: iter(value) except TypeError: raise NotAnIterator(value) class Orderable(object): """Values of ordered fields can be sorted. They can be restricted to a range of values. Orderable is a mixin used in combination with Field. """ min = ValidatedProperty('min') max = ValidatedProperty('max') def __init__(self, min=None, max=None, default=None, **kw): # Set min and max to None so that we can validate if # one of the super methods invoke validation. self.min = None self.max = None super(Orderable, self).__init__(**kw) # Now really set min and max self.min = min self.max = max # We've taken over setting default so it can be limited by min # and max. self.default = default def _validate(self, value): super(Orderable, self)._validate(value) if self.min is not None and value < self.min: raise TooSmall(value, self.min) if self.max is not None and value > self.max: raise TooBig(value, self.max) class MinMaxLen(object): """Expresses constraints on the length of a field. MinMaxLen is a mixin used in combination with Field. """ min_length = 0 max_length = None def __init__(self, min_length=0, max_length=None, **kw): self.min_length = min_length self.max_length = max_length super(MinMaxLen, self).__init__(**kw) def _validate(self, value): super(MinMaxLen, self)._validate(value) if self.min_length is not None and len(value) < self.min_length: raise TooShort(value, self.min_length) if self.max_length is not None and len(value) > self.max_length: raise TooLong(value, self.max_length) class Text(MinMaxLen, Field): """A field containing text used for human discourse.""" _type = unicode implements(IFromUnicode) def __init__(self, *args, **kw): super(Text, self).__init__(*args, **kw) def fromUnicode(self, str): """ >>> t = Text(constraint=lambda v: 'x' in v) >>> t.fromUnicode("foo x spam") Traceback (most recent call last): ... WrongType: ('foo x spam', ) >>> t.fromUnicode(u"foo x spam") u'foo x spam' >>> t.fromUnicode(u"foo spam") Traceback (most recent call last): ... ConstraintNotSatisfied: foo spam """ self.validate(str) return str class TextLine(Text): """A text field with no newlines.""" def constraint(self, value): return '\n' not in value and '\r' not in value class Password(TextLine): """A text field containing a text used as a password.""" class Bool(Field): """A field representing a Bool.""" _type = type(True) if _type is not type(1): # Python 2.2.1 and newer 2.2.x releases, True and False are # integers, and bool() returns either 1 or 0. We need to # support using integers here so we don't invalidate schema # that were perfectly valid with older versions of Python. def _validate(self, value): # Convert integers to bools to they don't get mis-flagged # by the type check later. if isinstance(value, int): value = bool(value) Field._validate(self, value) def set(self, object, value): if isinstance(value, int): value = bool(value) Field.set(self, object, value) def fromUnicode(self, str): """ >>> b = Bool() >>> b.fromUnicode('True') True >>> b.fromUnicode('') False >>> b.fromUnicode('true') True >>> b.fromUnicode('false') or b.fromUnicode('False') False """ v = str == 'True' or str == 'true' self.validate(v) return v class Int(Orderable, Field): """A field representing an Integer.""" _type = int, long implements(IFromUnicode) def __init__(self, *args, **kw): super(Int, self).__init__(*args, **kw) def fromUnicode(self, str): """ >>> f = Int() >>> f.fromUnicode("125") 125 >>> f.fromUnicode("125.6") Traceback (most recent call last): ... ValueError: invalid literal for int(): 125.6 """ v = int(str) self.validate(v) return v PKl4lMMzope/schema/fieldproperty.py############################################################################## # # Copyright (c) 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. # ############################################################################## """Computed attributes based on schema fields $Id: fieldproperty.py 25177 2004-06-02 13:17:31Z jim $ """ _marker = object() class FieldProperty(object): """Computed attributes based on schema fields Field properties provide default values, data validation and error messages based on data found in field meta-data. Note that FieldProperties cannot be used with slots. They can only be used for attributes stored in instance dictionaries. """ def __init__(self, field, name=None): if name is None: name = field.__name__ self.__field = field self.__name = name def __get__(self, inst, klass): if inst is None: return self value = inst.__dict__.get(self.__name, _marker) if value is _marker: field = self.__field.bind(inst) value = getattr(field, 'default', _marker) if value is _marker: raise AttributeError, self.__name return value def __set__(self, inst, value): field = self.__field.bind(inst) field.validate(value) inst.__dict__[self.__name] = value def __getattr__(self, name): return getattr(self.__field, name) PKl46Lzope/schema/__init__.py############################################################################## # # Copyright (c) 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. # ############################################################################## """Schema package constructor $Id: __init__.py 25177 2004-06-02 13:17:31Z jim $ """ from zope.schema._field import Field, Container, Iterable, Orderable from zope.schema._field import MinMaxLen, Choice from zope.schema._field import Bytes, ASCII, BytesLine from zope.schema._field import Text, TextLine, Bool, Int, Float from zope.schema._field import Tuple, List, Set from zope.schema._field import Password, Dict, Datetime, Date, SourceText from zope.schema._field import Object, URI, Id, DottedName from zope.schema._field import InterfaceField from zope.schema._schema import getFields, getFieldsInOrder from zope.schema._schema import getFieldNames, getFieldNamesInOrder from zope.schema.accessors import accessors from zope.schema.interfaces import ValidationError PKl4zope/schema/_schema.py############################################################################## # # Copyright (c) 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. # ############################################################################## """Schema convenience functions $Id: _schema.py 27082 2004-08-12 20:03:58Z srichter $ """ def getFieldNames(schema): """Return a list of all the Field names in a schema. """ from zope.schema.interfaces import IField return [name for name in schema if IField.providedBy(schema[name])] def getFields(schema): """Return a dictionary containing all the Fields in a schema. """ from zope.schema.interfaces import IField fields = {} for name in schema: attr = schema[name] if IField.providedBy(attr): fields[name] = attr return fields def getFieldsInOrder(schema, _fieldsorter=lambda x, y: cmp(x[1].order, y[1].order)): """Return a list of (name, value) tuples in native schema order. """ fields = getFields(schema).items() fields.sort(_fieldsorter) return fields def getFieldNamesInOrder(schema): """Return a list of all the Field names in a schema in schema order. """ return [ name for name, field in getFieldsInOrder(schema) ] PKl4ﵦiPPzope/schema/_field.py# -*- coding: ISO-8859-1 -*- ############################################################################## # # Copyright (c) 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. # ############################################################################## """Schema Fields $Id: _field.py 27056 2004-08-12 16:09:51Z srichter $ """ import warnings import re from datetime import datetime, date from sets import Set as SetType from zope.interface import classImplements, implements, directlyProvides from zope.interface.interfaces import IInterface, IMethod from zope.schema.interfaces import IField from zope.schema.interfaces import IMinMaxLen, IText, ITextLine from zope.schema.interfaces import ISourceText from zope.schema.interfaces import IInterfaceField from zope.schema.interfaces import IBytes, IASCII, IBytesLine from zope.schema.interfaces import IBool, IInt, IFloat, IDatetime from zope.schema.interfaces import IChoice, ITuple, IList, ISet, IDict from zope.schema.interfaces import IPassword, IObject, IDate from zope.schema.interfaces import IURI, IId, IFromUnicode from zope.schema.interfaces import IVocabulary from zope.schema.interfaces import ValidationError, InvalidValue from zope.schema.interfaces import WrongType, WrongContainedType, NotUnique from zope.schema.interfaces import SchemaNotProvided, SchemaNotFullyImplemented from zope.schema.interfaces import InvalidURI, InvalidId, InvalidDottedName from zope.schema.interfaces import ConstraintNotSatisfied from zope.schema.interfaces import Unbound from zope.schema._bootstrapfields import Field, Container, Iterable, Orderable from zope.schema._bootstrapfields import MinMaxLen from zope.schema._bootstrapfields import Text, TextLine, Bool, Int, Password from zope.schema._bootstrapfields import MinMaxLen, ValidatedProperty from zope.schema.fieldproperty import FieldProperty from zope.schema.vocabulary import getVocabularyRegistry from zope.schema.vocabulary import SimpleTerm, SimpleVocabulary # Fix up bootstrap field types Field.title = FieldProperty(IField['title']) Field.description = FieldProperty(IField['description']) Field.required = FieldProperty(IField['required']) Field.readonly = FieldProperty(IField['readonly']) # Default is already taken care of classImplements(Field, IField) MinMaxLen.min_length = FieldProperty(IMinMaxLen['min_length']) MinMaxLen.max_length = FieldProperty(IMinMaxLen['max_length']) classImplements(Text, IText) classImplements(TextLine, ITextLine) classImplements(Password, IPassword) classImplements(Bool, IBool) classImplements(Int, IInt) class SourceText(Text): __doc__ = ISourceText.__doc__ implements(ISourceText) _type = unicode class Bytes(MinMaxLen, Field): __doc__ = IBytes.__doc__ implements(IBytes, IFromUnicode) _type = str def fromUnicode(self, u): """ >>> b = Bytes(constraint=lambda v: 'x' in v) >>> b.fromUnicode(u" foo x.y.z bat") ' foo x.y.z bat' >>> b.fromUnicode(u" foo y.z bat") Traceback (most recent call last): ... ConstraintNotSatisfied: foo y.z bat """ v = str(u) self.validate(v) return v class ASCII(Bytes): __doc__ = IASCII.__doc__ implements(IASCII) def _validate(self, value): """ >>> ascii = ASCII() Make sure we accept empty strings: >>> empty = '' >>> ascii._validate(empty) and all kinds of alphanumeric strings: >>> alphanumeric = "Bob\'s my 23rd uncle" >>> ascii._validate(alphanumeric) >>> umlauts = "Khlerstrae" >>> ascii._validate(umlauts) Traceback (most recent call last): ... InvalidValue """ super(ASCII, self)._validate(value) if not value: return if not max(map(ord, value)) < 128: raise InvalidValue class BytesLine(Bytes): """A Text field with no newlines.""" implements(IBytesLine) def constraint(self, value): # TODO: we should probably use a more general definition of newlines return '\n' not in value class Float(Orderable, Field): __doc__ = IFloat.__doc__ implements(IFloat, IFromUnicode) _type = float def __init__(self, *args, **kw): super(Float, self).__init__(*args, **kw) def fromUnicode(self, u): """ >>> f = Float() >>> f.fromUnicode("1.25") 1.25 >>> f.fromUnicode("1.25.6") Traceback (most recent call last): ... ValueError: invalid literal for float(): 1.25.6 """ v = float(u) self.validate(v) return v class Datetime(Orderable, Field): __doc__ = IDatetime.__doc__ implements(IDatetime) _type = datetime def __init__(self, *args, **kw): super(Datetime, self).__init__(*args, **kw) class Date(Orderable, Field): __doc__ = IDate.__doc__ implements(IDate) _type = date class Choice(Field): """Choice fields can have a value found in a constant or dynamic set of values given by the field definition. """ implements(IChoice) def __init__(self, values=None, vocabulary=None, **kw): """Initialize object.""" assert not (values is None and vocabulary is None), \ "You must specify either values or vocabulary." assert values is None or vocabulary is None, \ "You cannot specify both values and vocabulary." self.vocabulary = None self.vocabularyName = None if values is not None: self.vocabulary = SimpleVocabulary.fromValues(values) elif isinstance(vocabulary, (unicode, str)): self.vocabularyName = vocabulary else: assert IVocabulary.providedBy(vocabulary) self.vocabulary = vocabulary # Before a default value is checked, it is validated. However, a # named vocabulary is usually not complete when these fields are # initialized. Therefore signal the validation method to ignore # default value checks during initialization of a Choice tied to a # registered vocabulary. self._init_field = bool(self.vocabularyName) super(Choice, self).__init__(**kw) self._init_field = False def bind(self, object): """See zope.schema._bootstrapinterfaces.IField.""" clone = super(Choice, self).bind(object) # get registered vocabulary if needed: if clone.vocabulary is None and self.vocabularyName is not None: vr = getVocabularyRegistry() clone.vocabulary = vr.get(object, self.vocabularyName) return clone def fromUnicode(self, str): """ >>> from vocabulary import SimpleVocabulary >>> t = Choice( ... vocabulary=SimpleVocabulary.fromValues([u'foo',u'bar'])) >>> t.fromUnicode(u"baz") Traceback (most recent call last): ... ConstraintNotSatisfied: baz >>> t.fromUnicode(u"foo") u'foo' """ self.validate(str) return str def _validate(self, value): # Pass all validations during initialization if self._init_field: return super(Choice, self)._validate(value) vocabulary = self.vocabulary if vocabulary is None: vr = getVocabularyRegistry() try: vocabulary = vr.get(None, self.vocabularyName) except VocabularyRegistryError: raise ValueError("Can't validate value without vocabulary") if value not in vocabulary: raise ConstraintNotSatisfied, value class InterfaceField(Field): __doc__ = IInterfaceField.__doc__ implements(IInterfaceField) def _validate(self, value): super(InterfaceField, self)._validate(value) if not IInterface.providedBy(value): raise WrongType def _validate_sequence(value_type, value, errors=None): """Validates a sequence value. Returns a list of validation errors generated during the validation. If no errors are generated, returns an empty list. value_type is a field. value is the sequence being validated. errors is an optional list of errors that will be prepended to the return value. To illustrate, we'll use a text value type. All values must be unicode. >>> field = TextLine(required=True) To validate a sequence of various values: >>> errors = _validate_sequence(field, ('foo', u'bar', 1)) >>> errors [foo , 1 ] The only valid value in the sequence is the second item. The others generated errors. We can use the optional errors argument to collect additional errors for a new sequence: >>> errors = _validate_sequence(field, (2, u'baz'), errors) >>> errors [foo , 1 , 2 ] """ if errors is None: errors = [] if value_type is None: return errors for item in value: try: value_type.validate(item) except ValidationError, error: errors.append(error) return errors def _validate_uniqueness(value): temp_values = [] for item in value: if item in temp_values: raise NotUnique, item temp_values.append(item) class AbstractCollection(MinMaxLen, Iterable, Field): value_type = None unique = False def __init__(self, value_type=None, unique=False, **kw): super(AbstractCollection, self).__init__(**kw) # whine if value_type is not a field if value_type is not None and not IField.providedBy(value_type): raise ValueError, "'value_type' must be field instance." self.value_type = value_type self.unique = unique def bind(self, object): """See zope.schema._bootstrapinterfaces.IField.""" clone = super(AbstractCollection, self).bind(object) # binding value_type is necessary for choices with named vocabularies, # and possibly also for other fields. if clone.value_type is not None: clone.value_type = clone.value_type.bind(object) return clone def _validate(self, value): super(AbstractCollection, self)._validate(value) errors = _validate_sequence(self.value_type, value) if errors: raise WrongContainedType, errors if self.unique: _validate_uniqueness(value) class Tuple(AbstractCollection): """A field representing a Tuple.""" implements(ITuple) _type = tuple class List(AbstractCollection): """A field representing a List.""" implements(IList) _type = list class Set(AbstractCollection): """A field representing a set.""" implements(ISet) _type = SetType def __init__(self, **kw): if 'unique' in kw: # set members are always unique raise TypeError( "__init__() got an unexpected keyword argument 'unique'") super(Set, self).__init__(unique=True, **kw) def _validate_fields(schema, value, errors=None): if errors is None: errors = [] for name in schema.names(all=True): if not IMethod.providedBy(schema[name]): try: attribute = schema[name] if IField.providedBy(attribute): # validate attributes that are fields attribute.validate(getattr(value, name)) except ValidationError, error: errors.append(error) except AttributeError, error: # property for the given name is not implemented errors.append(SchemaNotFullyImplemented()) return errors class Object(Field): __doc__ = IObject.__doc__ implements(IObject) def __init__(self, schema, **kw): if not IInterface.providedBy(schema): raise WrongType self.schema = schema super(Object, self).__init__(**kw) def _validate(self, value): super(Object, self)._validate(value) # schema has to be provided by value if not self.schema.providedBy(value): raise SchemaNotProvided # check the value against schema errors = _validate_fields(self.schema, value) if errors: raise WrongContainedType(errors) class Dict(MinMaxLen, Iterable, Field): """A field representing a Dict.""" implements(IDict) _type = dict key_type = None value_type = None def __init__(self, key_type=None, value_type=None, **kw): super(Dict, self).__init__(**kw) # whine if key_type or value_type is not a field if key_type is not None and not IField.providedBy(key_type): raise ValueError, "'key_type' must be field instance." if value_type is not None and not IField.providedBy(value_type): raise ValueError, "'value_type' must be field instance." self.key_type = key_type self.value_type = value_type def _validate(self, value): super(Dict, self)._validate(value) errors = [] try: if self.value_type: errors = _validate_sequence(self.value_type, value.values(), errors) errors = _validate_sequence(self.key_type, value, errors) if errors: raise WrongContainedType, errors finally: errors = None _isuri = re.compile( r"[a-zA-z0-9+.-]+:" # scheme r"\S*$" # non space (should be pickier) ).match class URI(BytesLine): """URI schema field """ implements(IURI, IFromUnicode) def _validate(self, value): """ >>> uri = URI(__name__='test') >>> uri.validate("http://www.python.org/foo/bar") >>> uri.validate("DAV:") >>> uri.validate("www.python.org/foo/bar") Traceback (most recent call last): ... InvalidURI: www.python.org/foo/bar """ super(URI, self)._validate(value) if _isuri(value): return raise InvalidURI, value def fromUnicode(self, value): """ >>> uri = URI(__name__='test') >>> uri.fromUnicode("http://www.python.org/foo/bar") 'http://www.python.org/foo/bar' >>> uri.fromUnicode(" http://www.python.org/foo/bar") 'http://www.python.org/foo/bar' >>> uri.fromUnicode(" \\n http://www.python.org/foo/bar\\n") 'http://www.python.org/foo/bar' >>> uri.fromUnicode("http://www.python.org/ foo/bar") Traceback (most recent call last): ... InvalidURI: http://www.python.org/ foo/bar """ v = str(value.strip()) self.validate(v) return v _isdotted = re.compile( r"([a-zA-Z][a-zA-z0-9_]*)" r"([.][a-zA-Z][a-zA-z0-9_]*)*" r"$" # use the whole line ).match class Id(BytesLine): """Id field Values of id fields must be either uris or dotted names. """ implements(IId, IFromUnicode) def _validate(self, value): """ >>> id = Id(__name__='test') >>> id.validate("http://www.python.org/foo/bar") >>> id.validate("zope.app.content") >>> id.validate("zope.app.content/a") Traceback (most recent call last): ... InvalidId: zope.app.content/a >>> id.validate("http://zope.app.content x y") Traceback (most recent call last): ... InvalidId: http://zope.app.content x y """ super(Id, self)._validate(value) if _isuri(value): return if _isdotted(value) and "." in value: return raise InvalidId, value def fromUnicode(self, value): """ >>> id = Id(__name__='test') >>> id.fromUnicode("http://www.python.org/foo/bar") 'http://www.python.org/foo/bar' >>> id.fromUnicode(u" http://www.python.org/foo/bar ") 'http://www.python.org/foo/bar' >>> id.fromUnicode("http://www.python.org/ foo/bar") Traceback (most recent call last): ... InvalidId: http://www.python.org/ foo/bar >>> id.fromUnicode(" \\n x.y.z \\n") 'x.y.z' """ v = str(value.strip()) self.validate(v) return v class DottedName(BytesLine): """Dotted name field. Values of DottedName fields must be Python-style dotted names. """ def __init__(self, *args, **kw): """ >>> DottedName(min_dots=-1) Traceback (most recent call last): ... ValueError: min_dots cannot be less than zero >>> DottedName(max_dots=-1) Traceback (most recent call last): ... ValueError: max_dots cannot be less than min_dots >>> DottedName(max_dots=1, min_dots=2) Traceback (most recent call last): ... ValueError: max_dots cannot be less than min_dots >>> dotted_name = DottedName(max_dots=1, min_dots=1) >>> dotted_name = DottedName(max_dots=1) >>> dotted_name.min_dots 0 >>> dotted_name = DottedName(min_dots=1) >>> dotted_name.max_dots >>> dotted_name.min_dots 1 """ self.min_dots = int(kw.pop("min_dots", 0)) if self.min_dots < 0: raise ValueError("min_dots cannot be less than zero") self.max_dots = kw.pop("max_dots", None) if self.max_dots is not None: self.max_dots = int(self.max_dots) if self.max_dots < self.min_dots: raise ValueError("max_dots cannot be less than min_dots") super(DottedName, self).__init__(*args, **kw) def _validate(self, value): """ >>> dotted_name = DottedName(__name__='test') >>> dotted_name.validate("a.b.c") >>> dotted_name.validate("a") >>> dotted_name.validate(" a ") Traceback (most recent call last): ... InvalidDottedName: a >>> dotted_name = DottedName(__name__='test', min_dots=1) >>> dotted_name.validate('a.b') >>> dotted_name.validate('a.b.c.d') >>> dotted_name.validate('a') Traceback (most recent call last): ... InvalidDottedName: ('too few dots; 1 required', 'a') >>> dotted_name = DottedName(__name__='test', max_dots=0) >>> dotted_name.validate('a') >>> dotted_name.validate('a.b') Traceback (most recent call last): ... InvalidDottedName: ('too many dots; no more than 0 allowed', 'a.b') >>> dotted_name = DottedName(__name__='test', max_dots=2) >>> dotted_name.validate('a') >>> dotted_name.validate('a.b') >>> dotted_name.validate('a.b.c') >>> dotted_name.validate('a.b.c.d') Traceback (most recent call last): ... InvalidDottedName: ('too many dots; no more than 2 allowed', 'a.b.c.d') >>> dotted_name = DottedName(__name__='test', max_dots=1, min_dots=1) >>> dotted_name.validate('a.b') >>> dotted_name.validate('a') Traceback (most recent call last): ... InvalidDottedName: ('too few dots; 1 required', 'a') >>> dotted_name.validate('a.b.c') Traceback (most recent call last): ... InvalidDottedName: ('too many dots; no more than 1 allowed', 'a.b.c') """ super(DottedName, self)._validate(value) if not _isdotted(value): raise InvalidDottedName(value) dots = value.count(".") if dots < self.min_dots: raise InvalidDottedName, \ ("too few dots; %d required" % self.min_dots, value) if self.max_dots is not None and dots > self.max_dots: raise InvalidDottedName, \ ("too many dots; no more than %d allowed" % self.max_dots, value) def fromUnicode(self, value): v = str(value.strip()) self.validate(v) return v PKl4' #zope/schema/_bootstrapinterfaces.py############################################################################## # # Copyright (c) 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. # ############################################################################## """Bootstrap schema interfaces and exceptions $Id: _bootstrapinterfaces.py 25177 2004-06-02 13:17:31Z jim $ """ import zope.interface from zope.i18nmessageid import MessageIDFactory _ = MessageIDFactory("zope") class StopValidation(Exception): """Raised if the validation is completed early. Note that this exception should be always caught, since it is just a way for the validator to save time. """ class ValidationError(zope.interface.Invalid): """Raised if the Validation process fails.""" def doc(self): return self.__class__.__doc__ def __cmp__(self, other): return cmp(self.args, other.args) def __repr__(self): return ' '.join(map(str, self.args)) class RequiredMissing(ValidationError): __doc__ = _("""Required input is missing.""") class WrongType(ValidationError): __doc__ = _("""Object is of wrong type.""") class TooBig(ValidationError): __doc__ = _("""Value is too big""") class TooSmall(ValidationError): __doc__ = _("""Value is too small""") class TooLong(ValidationError): __doc__ = _("""Value is too long""") class TooShort(ValidationError): __doc__ = _("""Value is too short""") class InvalidValue(ValidationError): __doc__ = _("""Invalid value""") class ConstraintNotSatisfied(ValidationError): __doc__ = _("""Constraint not satisfied""") class NotAContainer(ValidationError): __doc__ = _("""Not a container""") class NotAnIterator(ValidationError): __doc__ = _("""Not an iterator""") class IFromUnicode(zope.interface.Interface): """Parse a unicode string to a value We will often adapt fields to this interface to support views and other applications that need to conver raw data as unicode values. """ def fromUnicode(str): """Convert a unicode string to a value. """ PKl4 Hl?l?zope/schema/interfaces.py############################################################################## # # Copyright (c) 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. # ############################################################################## """Schema interfaces and exceptions $Id: interfaces.py 28315 2004-11-01 23:30:26Z fdrake $ """ from zope.interface import Interface, Attribute from zope.schema._bootstrapfields import Field, Text, TextLine, Bool, Int from zope.schema._bootstrapfields import Container, Iterable from zope.i18nmessageid import MessageIDFactory _ = MessageIDFactory("zope") # Import from _bootstrapinterfaces only because other packages will expect # to find these interfaces here. from zope.schema._bootstrapinterfaces import StopValidation, ValidationError from zope.schema._bootstrapinterfaces import IFromUnicode from zope.schema._bootstrapinterfaces import RequiredMissing, WrongType from zope.schema._bootstrapinterfaces import ConstraintNotSatisfied from zope.schema._bootstrapinterfaces import NotAContainer, NotAnIterator from zope.schema._bootstrapinterfaces import TooSmall, TooBig from zope.schema._bootstrapinterfaces import TooShort, TooLong from zope.schema._bootstrapinterfaces import InvalidValue class WrongContainedType(ValidationError): __doc__ = _("""Wrong contained type""") class NotUnique(ValidationError): __doc__ = _("""One or more entries of sequence are not unique.""") class SchemaNotFullyImplemented(ValidationError): __doc__ = _("""Schema not fully implemented""") class SchemaNotProvided(ValidationError): __doc__ = _("""Schema not provided""") class InvalidURI(ValidationError): __doc__ = _("""The specified URI is not valid.""") class InvalidId(ValidationError): __doc__ = _("""The specified id is not valid.""") class InvalidDottedName(ValidationError): __doc__ = _("""The specified dotted name is not valid.""") class Unbound(Exception): __doc__ = _("""The field is not bound.""") class IField(Interface): """Basic Schema Field Interface. Fields are used for Interface specifications. They at least provide a title, description and a default value. You can also specify if they are required and/or readonly. The Field Interface is also used for validation and specifying constraints. We want to make it possible for a IField to not only work on its value but also on the object this value is bound to. This enables a Field implementation to perform validation against an object which also marks a certain place. Note that many fields need information about the object containing a field. For example, when validating a value to be set as an object attribute, it may be necessary for the field to introspect the object's state. This means that the field needs to have access to the object when performing validation:: bound = field.bind(object) bound.validate(value) """ def bind(object): """Return a copy of this field which is bound to context. The copy of the Field will have the 'context' attribute set to 'object'. This way a Field can implement more complex checks involving the object's location/environment. Many fields don't need to be bound. Only fields that condition validation or properties on an object containing the field need to be bound. """ title = TextLine( title=_(u"Title"), description=_(u"A short summary or label"), default=u"", required=False, ) description = Text( title=_(u"Description"), description=_(u"A description of the field"), default=u"", required=False, ) required = Bool( title=_(u"Required"), description=( _(u"Tells whether a field requires its value to exist.")), default=True) readonly = Bool( title=_(u"Read Only"), description=_(u"If true, the field's value cannot be changed."), required=False, default=False) default = Field( title=_(u"Default Value"), description=_(u"""The field default value may be None or a legal field value""") ) missing_value = Field( title=_(u"Missing Value"), description=_(u"""If input for this Field is missing, and that's ok, then this is the value to use""") ) order = Int( title=_(u"Field Order"), description=_(u"""\ The order attribute can be used to determine the order in which fields in a schema were defined. If one field is created after another (in the same thread), its order will be greater. (Fields in separate threads could have the same order.) """), required=True, readonly=True, ) def constraint(value): u"""Check a customized constraint on the value. You can implement this method with your Field to require a certain constraint. This relaxes the need to inherit/subclass a Field you to add a simple constraint. Returns true if the given value is within the Field's constraint. """ def validate(value): u"""Validate that the given value is a valid field value. Returns nothing but raises an error if the value is invalid. It checks everything specific to a Field and also checks with the additional constraint. """ def get(object): """Get the value of the field for the given object.""" def query(object, default=None): """Query the value of the field for the given object. Return the default if the value hasn't been set. """ def set(object, value): """Set the value of the field for the object Raises a type error if the field is a read-only field. """ class IIterable(IField): u"""Fields with a value that can be iterated over. The value needs to support iteration; the implementation mechanism is not constrained. (Either __iter__() or __getitem__() may be used.) """ class IContainer(IField): u"""Fields whose value allows an 'x in value' check. The Value needs to support the 'in' operator, but is not constrained in how it does so (whether it defines __contains__() or __getitem__() is immaterial). """ class IOrderable(IField): u"""Field requiring its value to be orderable. The set of value needs support a complete ordering; the implementation mechanism is not constrained. Either __cmp__() or 'rich comparison' methods may be used. """ class ILen(IField): u"""A Field requiring its value to have a length. The value needs to have a conventional __len__ method. """ class IMinMax(IOrderable): u"""Field requiring its value to be between min and max. This implies that the value needs to support the IOrderable interface. """ min = Field( title=_(u"Start of the range"), required=False, default=None ) max = Field( title=_(u"End of the range (excluding the value itself)"), required=False, default=None ) class IMinMaxLen(ILen): u"""Field requiring the length of its value to be within a range""" min_length = Int( title=_(u"Minimum length"), description=_(u"""\ Value after whitespace processing cannot have less than min_length characters (if a string type) or elements (if another sequence type). If min_length is None, there is no minimum. """), required=False, min=0, # needs to be a positive number default=0) max_length = Int( title=_(u"Maximum length"), description=_(u"""\ Value after whitespace processing cannot have greater or equal than max_length characters (if a string type) or elements (if another sequence type). If max_length is None, there is no maximum."""), required=False, min=0, # needs to be a positive number default=None) class IInterfaceField(IField): u"""Fields with a value that is an interface (implementing zope.interface.Interface).""" class IBool(IField): u"""Boolean Field.""" default = Bool( title=_(u"Default Value"), description=_(u"""The field default value may be None or a legal field value""") ) class IBytes(IMinMaxLen, IIterable, IField): u"""Field containing a byte string (like the python str). The value might be constrained to be with length limits. """ class IASCII(IBytes): u"""Field containing a 7-bit ASCII string. No characters > DEL (chr(127)) are allowed The value might be constrained to be with length limits. """ class IBytesLine(IBytes): u"""Field containing a byte string without newlines.""" class IText(IMinMaxLen, IIterable, IField): u"""Field containing a unicode string.""" class ISourceText(IText): u"""Field for source text of object.""" class ITextLine(IText): u"""Field containing a unicode string without newlines.""" class IPassword(ITextLine): u"Field containing a unicode string without newlines that is a password." class IInt(IMinMax, IField): u"""Field containing an Integer Value.""" min = Int( title=_(u"Start of the range"), required=False, default=None ) max = Int( title=_(u"End of the range (excluding the value itself)"), required=False, default=None ) default = Int( title=_(u"Default Value"), description=_(u"""The field default value may be None or a legal field value""") ) class IFloat(IMinMax, IField): u"""Field containing a Float.""" class IDatetime(IMinMax, IField): u"""Field containing a DateTime.""" class IDate(IMinMax, IField): u"""Field containing a date.""" def _is_field(value): if not IField.providedBy(value): return False return True def _fields(values): for value in values: if not _is_field(value): return False return True class IURI(IBytesLine): """A field containing an absolute URI """ class IId(IBytesLine): """A field containing a unique identifier A unique identifier is either an absolute URI or a dotted name. If it's a dotted name, it should have a module/package name as a prefix. """ class IChoice(IField): u"""Field whose value is contained in a predefined set Only one, values or vocabulary, may be specified for a given choice. """ vocabularyName = TextLine( title=u"Vocabulary Name", description=(u"The name of the vocabulary to be used. This name\n" u"is intended to be used by the IVocabularyRegistry's\n" u"get() method."), required=False, default=None) vocabulary = Attribute( "vocabulary", ("IBaseVocabulary to be used, or None.\n" "\n" "If None, the vocabularyName should be used by an\n" "IVocabularyRegistry should be used to locate an appropriate\n" "IBaseVocabulary object.")) # Collections: # Abstract class ICollection(IMinMaxLen, IIterable, IContainer): u"""Abstract interface containing a collection value. The Value must be iterable and may have a min_length/max_length. """ value_type = Field( title = _("Value Type"), description = _(u"Field value items must conform to the given type, " u"expressed via a Field.")) unique = Bool( title = _('Unique Members'), description = _('Specifies whether the members of the collection ' 'must be unique.'), default=False) class ISequence(ICollection): u"""Abstract interface specifying that the value is ordered""" class IUnorderedCollection(ICollection): u"""Abstract interface specifying that the value cannot be ordered""" # Concrete class ITuple(ISequence): u"""Field containing a value that implements the API of a conventional Python tuple.""" class IList(ISequence): u"""Field containing a value that implements the API of a conventional Python list.""" class ISet(IUnorderedCollection): u"""Field containing a value that implements the API of a conventional Python standard library sets.Set.""" unique = Attribute(u"This ICollection interface attribute must be True") # (end Collections) class IObject(IField): u"""Field containing an Object value.""" schema = Attribute("schema", _(u"The Interface that defines the Fields comprising the Object.")) class IDict(IMinMaxLen, IIterable, IContainer): u"""Field containing a conventional dict. The key_type and value_type fields allow specification of restrictions for keys and values contained in the dict. """ key_type = Attribute("key_type", _(u"""Field keys must conform to the given type, expressed via a Field. """)) value_type = Attribute("value_type", _(u"""Field values must conform to the given type, expressed via a Field. """)) class ITerm(Interface): """Object representing a single value in a vocabulary.""" value = Attribute( "value", "The value used to represent vocabulary term in a field.") class ITokenizedTerm(ITerm): """Object representing a single value in a tokenized vocabulary. """ token = Attribute( "token", """Token which can be used to represent the value on a stream. The value of this attribute must be a non-empty 7-bit string. Control characters are not allowed. """) class ITitledTokenizedTerm(ITokenizedTerm): """A tokenized term that includes a title.""" title = TextLine(title=_(u"Title")) class IBaseVocabulary(Interface): """Representation of a vocabulary. At this most basic level, a vocabulary only need to support a test for containment. This can be implemented either by __contains__() or by sequence __getitem__() (the later only being useful for vocabularies which are intrinsically ordered). """ def __contains__(value): """Returns True if the value is available in this vocabulary.""" def getTerm(value): """Return the ITerm object for the term 'value'. If 'value' is not a valid term, this method raises LookupError. """ class IIterableVocabulary(Interface): """Vocabulary which supports iteration over allowed values. The objects iteration provides must conform to the ITerm interface. """ def __iter__(): """Return an iterator which provides the terms from the vocabulary.""" def __len__(): """Return the number of valid terms, or sys.maxint.""" class IVocabulary(IIterableVocabulary, IBaseVocabulary): """Vocabulary which is iterable.""" class IVocabularyTokenized(IVocabulary): """Vocabulary that provides support for tokenized representation. This interface must be used as a mix-in with IBaseVocabulary. Terms returned from getTerm() and provided by iteration must conform to ITitledTokenizedTerm. """ def getTermByToken(token): """Return an ITokenizedTerm for the passed-in token.""" class IVocabularyRegistry(Interface): """Registry that provides IBaseVocabulary objects for specific fields. """ def get(object, name): """Return the vocabulary named 'name' for the content object 'object'. When the vocabulary cannot be found, LookupError is raised. """ PKl4ǩ zope/schema/accessors.py############################################################################## # # Copyright (c) 2003 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. # ############################################################################## """\ Field accessors =============== Accessors are used to model methods used to access data defined by fields. Accessors are fields that work by decorating existing fields. To define accessors in an interface, use the accessors function:: class IMyInterface(Interface): getFoo, setFoo = accessors(Text(title=u'Foo', ...)) getBar, = accessors(TextLine(title=u'Foo', readonly=True, ...) Normally a read accessor and a write accessor are defined. Only a read accessor is defined for read-only fields. Read accessors function as access method specifications and as field specifications. Write accessors are solely method specifications. $Id: accessors.py 25177 2004-06-02 13:17:31Z jim $ """ from zope.interface import providedBy, implementedBy from zope.interface.interface import Method class FieldReadAccessor(Method): """Field read accessor """ # A read field accessor is a method and a field. # A read accessor is a decorator of a field, using the given # fields properties to provide meta data. def __provides__(self): return providedBy(self.field) + implementedBy(FieldReadAccessor) __provides__ = property(__provides__) def __init__(self, field): self.field = field Method.__init__(self, '') self.__doc__ = 'get %s' % field.__doc__ def getSignatureString(self): return '()' def getSignatureInfo(self): return {'positional': (), 'required': (), 'optional': (), 'varargs': None, 'kwargs': None, } def get(self, object): return getattr(object, self.__name__)() def query(self, object, default=None): return getattr(object, self.__name__)() def set(self, object, value): if self.readonly: raise TypeError("Can't set values on read-only fields") getattr(object, self.writer.__name__)(value) def __getattr__(self, name): return getattr(self.field, name) def bind(self, object): clone = self.__class__.__new__(self.__class__) clone.__dict__.update(self.__dict__) clone.field = self.field.bind(object) return clone class FieldWriteAccessor(Method): def __init__(self, field): Method.__init__(self, '') self.field = field self.__doc__ = 'set %s' % field.__doc__ def getSignatureString(self): return '(newvalue)' def getSignatureInfo(self): return {'positional': ('newvalue',), 'required': ('newvalue',), 'optional': (), 'varargs': None, 'kwargs': None, } def accessors(field): reader = FieldReadAccessor(field) yield reader if not field.readonly: writer = FieldWriteAccessor(field) reader.writer = writer yield writer PKl4zope/schema/vocabulary.py############################################################################## # # Copyright (c) 2003 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. # ############################################################################## """Vocabulary support for schema. $Id: vocabulary.py 27726 2004-09-30 23:00:04Z jim $ """ from zope.interface.declarations import directlyProvides, implements from zope.schema.interfaces import ValidationError from zope.schema.interfaces import IVocabularyRegistry from zope.schema.interfaces import IVocabulary, IVocabularyTokenized from zope.schema.interfaces import ITokenizedTerm, ITitledTokenizedTerm # simple vocabularies performing enumerated-like tasks _marker = object() class SimpleTerm(object): """Simple tokenized term used by SimpleVocabulary.""" implements(ITokenizedTerm) def __init__(self, value, token=None, title=None): """Create a term for value and token. If token is omitted, str(value) is used for the token. If title is provided, term implements ITitledTokenizedTerm. """ self.value = value if token is None: token = value self.token = str(token) self.title = title if title is not None: directlyProvides(self, ITitledTokenizedTerm) class SimpleVocabulary(object): """Vocabulary that works from a sequence of terms.""" implements(IVocabulary, IVocabularyTokenized) def __init__(self, terms, *interfaces): """Initialize the vocabulary given a list of terms. The vocabulary keeps a reference to the list of terms passed in; it should never be modified while the vocabulary is used. One or more interfaces may also be provided so that alternate widgets may be bound without subclassing. """ self.by_value = {} self.by_token = {} self._terms = terms for term in self._terms: self.by_value[term.value] = term self.by_token[term.token] = term if not (len(self.by_value) == len(self.by_token) == len(terms)): raise ValueError( 'Supplied vocabulary values resulted in duplicate term tokens') if interfaces: directlyProvides(self, *interfaces) def fromItems(cls, items, *interfaces): """Construct a vocabulary from a list of (token, value) pairs. The order of the items is preserved as the order of the terms in the vocabulary. Terms are created by calling the class method createTerm() with the pair (value, token). One or more interfaces may also be provided so that alternate widgets may be bound without subclassing. """ terms = [cls.createTerm(value, token) for (token, value) in items] return cls(terms, *interfaces) fromItems = classmethod(fromItems) def fromValues(cls, values, *interfaces): """Construct a vocabulary from a simple list. Values of the list become both the tokens and values of the terms in the vocabulary. The order of the values is preserved as the order of the terms in the vocabulary. Tokens are created by calling the class method createTerm() with the value as the only parameter. One or more interfaces may also be provided so that alternate widgets may be bound without subclassing. """ terms = [cls.createTerm(value) for value in values] return cls(terms, *interfaces) fromValues = classmethod(fromValues) def createTerm(cls, *args): """Create a single term from data. Subclasses may override this with a class method that creates a term of the appropriate type from the arguments. """ return SimpleTerm(*args) createTerm = classmethod(createTerm) def __contains__(self, value): """See zope.schema.interfaces.IBaseVocabulary""" try: return value in self.by_value except TypeError: # sometimes values are not hashable return False def getTerm(self, value): """See zope.schema.interfaces.IBaseVocabulary""" try: return self.by_value[value] except KeyError: raise LookupError(value) def getTermByToken(self, token): """See zope.schema.interfaces.IVocabularyTokenized""" try: return self.by_token[token] except KeyError: raise LookupError(token) def __iter__(self): """See zope.schema.interfaces.IIterableVocabulary""" return iter(self._terms) def __len__(self): """See zope.schema.interfaces.IIterableVocabulary""" return len(self.by_value) # registry code class VocabularyRegistryError(LookupError): def __init__(self, name): self.name = name Exception.__init__(self, str(self)) def __str__(self): return "unknown vocabulary: %r" % self.name class VocabularyRegistry(object): __slots__ = '_map', implements(IVocabularyRegistry) def __init__(self): self._map = {} def get(self, object, name): """See zope.schema.interfaces.IVocabularyRegistry""" try: vtype = self._map[name] except KeyError: raise VocabularyRegistryError(name) return vtype(object) def register(self, name, factory): self._map[name] = factory _vocabularies = None def getVocabularyRegistry(): """Return the vocabulary registry. If the registry has not been created yet, an instance of VocabularyRegistry will be installed and used. """ if _vocabularies is None: setVocabularyRegistry(VocabularyRegistry()) return _vocabularies def setVocabularyRegistry(registry): """Set the vocabulary registry.""" global _vocabularies _vocabularies = registry def _clear(): """Remove the registries (for use by tests).""" global _vocabularies _vocabularies = None try: from zope.testing.cleanup import addCleanUp except ImportError: # don't have that part of Zope pass else: addCleanUp(_clear) del addCleanUp PKl4`//zope/schema/DEPENDENCIES.cfgzope.i18nmessageid zope.interface zope.testing PKl4[T " "zope/schema/README.txt============== Zope 3 Schemas ============== Introduction ------------ Schemas extend the notion of interfaces to descriptions of Attributes rather than methods. Every Schema is an interface and specifies the public fields of an object. A *Field* roughly corresponds to an attribute of a python object. But a Field provides space for a title and a description. It can also constrain its value and provide a validation method. Besides you can optionally specify characteristics such as its value being read-only or not required. Zope 3 schemas were born when Jim Fulton and Martijn Faassen thought about Formulator for Zope 3 and PropertySets while at the `Zope 3 sprint`_ at the `Zope BBQ`_ in Berlin. They realized that if you strip all view logic from forms than you have something to interfaces. And thus schemas were born. .. _Zope 3 sprint: http://dev.zope.org/Zope3/ZopeBBQ2002Sprint .. _Zope BBQ: http://www.beehive.de/zope/Events/ZopeBBQ2002.html Dependencies ------------ The ``zope.schema`` package only depends on the ``zope.interface`` package. Simple Usage ------------ :: $ python >>> class Bookmark: ... def __init__(self, url): ... self.url = url ... >>> from zope.schema import TextLine, validateMapping >>> from zope.interface import Interface >>> class IBookmark(Interface): ... url = TextLine(title=u'url of the bookmark') ... ... >>> obj = Bookmark(u'zope website', u'http://www.zope.org', ... keywords=('web', 'python')) >>> validateMapping(IBookmark, obj.__dict__) The last statement validates that our object conforms to the ``IBookmark`` Schema. What is a schema, how does it compare to an interface? ------------------------------------------------------ A schema is an extended interface which defines Fields. You can validate that attributes of an object conform to their Fields defined on the schema. With plain interfaces you can only validate that methods conform to their interface specification. So interfaces and schemas refer to different aspects of an object (respectively its code and state). A Schema starts out like an interface but defines certain Fields to which an object's attributes must conform. Let's look at a stripped down example from the programmer's tutorial (chapter two):: from zope.interface import Interface from zope.schema import Text, TextLine class IContact(Interface): """Provides access to basic contact information.""" first = TextLine(title=u"First name") last = TextLine(title=u"Last name") email = TextLine(title=u"Electronic mail address") address = Text(title=u"Postal address") postalCode = TextLine(title=u"Postal code", constraint=re.compile( "\d{5,5}(-\d{4,4})?$").match) ``TextLine`` is a field and expresses that an attribute is a single line of Unicode text. ``Text`` expresses an arbitrary Unicode ("text") object. The most interesting part is the last attribute specification. It constrains the ``postalCode`` attribute to only have values that are US postal codes. Now we want a class that adheres to the IContact Schema:: class Contact(persistent.Persistent): implements(IContact) def __init__(self, first, last, email, address, pc): self.first = first self.last = last self.email = email self.address = address self.postalCode = pc Now you can see if an instance of ``Contact`` actually implements the schema:: from zope.app.schema import validateMapping someone = Contact('Tim','Roberts', 'tim@roberts', '','') validateMapping(IContact, someone.__dict__) Data Modeling Concepts ----------------------- XXX much more is needed here! The ``zope.schema`` package provides a core set of field types, including single- and multi-line text fields, binary data fields, integers, floating-point numbers, and date/time values. Selection issues; field type can specify: - "Raw" data value Simple values not constrained by a selection list. - Value from enumeration (options provided by schema) This models a single selection from a list of possible values specified by the schema. The selection list is expected to be the same for all values of the type. Changes to the list are driven by schema evolution. This is done by mixing-in the IEnumerated interface into the field type, and the Enumerated mix-in for the implementation (or emulating it in a concrete class). - Value from selection list (options provided by an object) This models a single selection from a list of possible values specified by a source outside the schema. The selection list depends entirely on the source of the list, and may vary over time and from object to object. Changes to the list are not related to the schema, but changing how the list is determined is based on schema evolution. There is not currently a spelling of this, but it could be facilitated using alternate mix-ins similar to IEnumerated and Enumerated. - Whether or not the field is read-only If a field value is read-only, it cannot be changed once the object is created. - Whether or not the field is required If a field is designated as required, assigned field values must always be non-missing. See the next section for a description of missing values. - A value designated as 'missing' Missing values, when assigned to an object, indicate that there is 'no data' for that field. Missing values are analogous to null values in relational databases. For example, a boolean value can be True, False, or missing, in which case its value is unknown. While Python's None is the most likely value to signify 'missing', some fields may use different values. For example, it is common for text fields to use the empty string ('') to signify that a value is missing. Numeric fields may use 0 or -1 instead of None as their missing value. A field that is 'required' signifies that missing values are invalid and should not be assigned. - A default value Default field values are assigned to objects when they are first created. Fields and Widgets ------------------ Widgets are components that display field values and, in the case of writable fields, allow the user to edit those values. Widgets: - Display current field values, either in a read-only format, or in a format that lets the user change the field value. - Update their corresponding field values based on values provided by users. - Manage the relationships between their representation of a field value and the object's field value. For example, a widget responsible for editing a number will likely represent that number internally as a string. For this reason, widgets must be able to convert between the two value formats. In the case of the number-editing widget, string values typed by the user need to be converted to numbers such as int or float. - Support the ability to assign a missing value to a field. For example, a widget may present a "None" option for selection that, when selected, indicates that the object should be updated with the field's 'missing' value. Issues to be solved ------------------- These issues were written up at the `Rotterdam Sprint`_ (12/4/2002). .. _Rotterdam Sprint: http://dev.zope.org/Zope3/InfraeSprintathon I18n **** How i18n interferes with Schemas is not thought out. In a non-English context we probably want to have titles and descriptions easily translatable. The best idea so far is to use an attribute name together with its surrounding namespace (Interface-name etc.) as the message id used for looking up translations. Example:: class book(Interface): author = ITextLine() To get to the And in view, while the widget or widget's messages are constructed:: TranslatorService.getMessage('book.author.title', 'DE_DE') Integration with Interfaces *************************** How closely are Interfaces and Schema related? Should they be refactored into one package? Are Schemas Zope-specific? Clarify and clean up use cases ****************************** Some use cases are not easy to understand. A lot of them look like features rather than use cases. The list of schema use cases needs to be cleaned up and be (sometimes) more detailed. References ---------- - Use case list, http://dev.zope.org/Zope3/Zope3SchemasUseCases - Documented interfaces, zope/schema/interfaces.py - Jim Fulton's Programmers Tutorial; in CVS: Docs/ZopeComponentArchitecture/PythonProgrammerTutorial/Chapter2 PKl4#5Йzope/schema/fields.txt====== Fields ====== This document highlights unusual and subtle aspects of various fields and field classes, and is not intended to be a general introduction to schema fields. Please see README.txt for a more general introduction. While many field types, such as Int, TextLine, Text, and Bool are relatively straightforward, a few have some subtlety. We will explore the general class of collections and discuss how to create a custom creation field; discuss Choice fields, vocabularies, and their use with collections; and close with a look at the standard zope.app approach to using these fields to find views ("widgets"). Collections =========== Normal fields typically describe the API of the attribute--does it behave as a Python Int, or a Float, or a Bool--and various constraints to the model, such as a maximum or minimum value. Collection fields have additional requirements because they contain other types, which may also be described and constrained. For instance, imagine a list that contains non-negative floats and enforces uniqueness, In a schema, this might be written as follows:: >>> from zope.interface import Interface >>> from zope.schema import List, Float >>> class IInventoryItem(Interface): ... pricePoints = List( ... title=u"Price Points", ... unique=True, ... value_type=Float(title=u"Price", min=0) ... ) This indicates several things. - pricePoints is an attribute of objects that implement IInventoryItem. - The contents of pricePoints can be accessed and manipulated via a Python list API. - Each member of pricePoints must be a non-negative float. - Members cannot be duplicated within pricePoints: each must be must be unique. - The attribute and its contents have descriptive titles. Typically these would be message ids. This declaration creates a field that implements a number of interfaces, among them these:: >>> from zope.schema.interfaces import IList, ISequence, ICollection >>> IList.providedBy(IInventoryItem['pricePoints']) True >>> ISequence.providedBy(IInventoryItem['pricePoints']) True >>> ICollection.providedBy(IInventoryItem['pricePoints']) True Creating a custom collection field ---------------------------------- Ideally, custom collection fields have interfaces that inherit appropriately from either zope.schema.interfaces.ISequence or zope.schema.interfaces.IUnorderedCollection. Most collection fields should be able to subclass zope.schema._field.AbstractCollection to get the necessary behavior. Notice the behavior of the Set field in zope.schema._field: this would also be necessary to implement a Bag. Choices and Vocabularies ======================== Choice fields are the schema way of spelling enumerated fields and more. By providing a dynamically generated vocabulary, the choices available to a choice field can be contextually calculated. Simple choices do not have to explicitly use vocabularies:: >>> from zope.schema import Choice >>> f = Choice((640, 1028, 1600)) >>> f.validate(640) >>> f.validate(960) Traceback (most recent call last): ... ConstraintNotSatisfied: 960 >>> f.validate('bing') Traceback (most recent call last): ... ConstraintNotSatisfied: bing More complex choices will want to use registered vocabularies. Vocabularies have a simple interface, as defined in zope.schema.interfaces.IBaseVocabulary. A vocabulary must minimally be able to determine whether it contains a value, to create a term object for a value, and to return a query interface (or None) to find items in itself. Term objects are an abstraction that wraps a vocabulary value. The Zope application server typically needs a fuller interface that provides "tokens" on its terms: ASCII values that have a one-to-one relationship to the values when the vocabulary is asked to "getTermByToken". If a vocabulary is small, it can also support the IIterableVocabulary interface. If a vocabulary has been registered, then the choice merely needs to pass the vocabulary identifier to the "vocabulary" argument of the choice during instantiation. A start to a vocabulary implementation that may do all you need for many simple tasks may be found in zope.schema.vocabulary.SimpleVocabulary. Because registered vocabularies are simply callables passed a context, many registered vocabularies can simply be functions that rely on SimpleVocabulary:: >>> from zope.schema.vocabulary import SimpleVocabulary >>> def myDynamicVocabulary(context): ... v = dynamic_context_calculation_that_returns_an_iterable(context) ... return SimpleVocabulary.fromValues(v) ... The vocabulary interface is simple enough that writing a custom vocabulary is not too difficult itself. Choices and Collections ----------------------- Choices are a field type and can be used as a value_type for collections. Just as a collection of an "Int" value_type constrains members to integers, so a choice-based value type constrains members to choices within the Choice's vocabulary. Typically in the Zope application server widgets are found not only for the collection and the choice field but also for the vocabulary on which the choice is based. Using Choice and Collection Fields within a Widget Framework ============================================================ While fields support several use cases, including code documentation and data decription and even casting, a significant use case influencing their design is to support form generation--generating widgets for a field. Choice and collection fields are expected to be used within widget frameworks. The zope.app approach typically (but configurably) uses multiple dispatches to find widgets on the basis of various aspects of the fields. Widgets for all fields are found by looking up a browser view of the field providing an input or display widget view. Typically there is only a single "widget" registered for Choice fields. When it is looked up, it performs another dispatch--another lookup--for a widget registered for both the field and the vocabulary. This widget typically has enough information to render without a third dispatch. Collection fields may fire several dispatches. The first is the usual lookup by field. A single "widget" should be registered for ICollection, which does a second lookup by field and value_type constraint, if any, or, theoretically, if value_type is None, renders some absolutely generic collection widget that allows input of any value imaginable: a check-in of such a widget would be unexpected. This second lookup may find a widget that knows how to render, and stop. However, the value_type may be a choice, which will usually fire a third dispatch: a search for a browser widget for the collection field, the value_type field, and the vocabulary. Further lookups may even be configured on the basis of uniqueness and other constraints. This level of indirection may be unnecessary for some applications, and can be disabled with simple ZCML changes within `zope.app`. PK4]== zope/schema/_bootstrapfields.pyc; ]53Dc@sdZdklZlZlZdklZdklZdklZl Z dkl Z dkl Z l Z dkl Z lZdklZlZd klZd klZd efd YZd efdYZdefdYZdefdYZdefdYZdefdYZdeefdYZdefdYZdefdYZdefdYZdeefd YZd!S("sUBootstrapping fields $Id: _bootstrapfields.py 27082 2004-08-12 20:03:58Z srichter $ (s Attributes providedBys implements(sStopValidation(s IFromUnicode(sRequiredMissings WrongType(sConstraintNotSatisfied(s NotAContainers NotAnIterator(sTooSmallsTooBig(sTooShortsTooLong(s InvalidValue(s getFieldssValidatedPropertycBstZedZdZRS(NcCs||f|_dS(N(snameschecksselfs_info(sselfsnamescheck((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys__init__ scCs\|i\}}|tj o/|tj o|||qK|i|n||i|>> f = Field() >>> f.__doc__, f.title, f.description ('', u'', u'') >>> f = Field(title=u'sample') >>> f.__doc__, f.title, f.description (u'sample', u'sample', u'') >>> f = Field(title=u'sample', description=u'blah blah\nblah') >>> f.__doc__, f.title, f.description (u'sample\n\nblah blah\nblah', u'sample', u'blah blah\nblah') ss%s %siN(s__doc__stitles descriptionssupersFieldsselfs__init__s__name__srequiredsreadonlys constraintsNonesdefaultsorders missing_values_Field__missing_value_marker( sselfstitles descriptions__name__srequiredsreadonlys constraintsdefaults missing_values__doc__((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys__init__Fs(          cCs9|ii|i}|ii|i||_|SdS(N(sselfs __class__s__new__sclones__dict__supdatesobjectscontext(sselfsobjectsclone((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pysbind{s cCsS||ijo|io tqOn(y|i|Wntj onXdS(N(svaluesselfs missing_valuesrequiredsRequiredMissings _validatesStopValidation(sselfsvalue((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pysvalidates cCst|t|jotSnh}x't|D]}|it|q4Wd|jo |d=nx5|D]-}t ||t ||jotSqpqpWt SdS(Nsorder( stypesselfsothersFalsesnamess providedBys interfacesupdates getFieldssnamesgetattrsTrue(sselfsothersnamesnamess interface((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys__eq__s    cCs|i| SdS(N(sselfs__eq__sother(sselfsother((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys__ne__scCso|itj ot||i ot||in|itj o|i| ot|ndS(N(sselfs_typesNones isinstancesvalues WrongTypes constraintsConstraintNotSatisfied(sselfsvalue((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys _validates$!cCst||iSdS(N(sgetattrsobjectsselfs__name__(sselfsobject((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pysgetscCst||i|SdS(N(sgetattrsobjectsselfs__name__sdefault(sselfsobjectsdefault((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pysqueryscCsM|io,td|i|ii|iifnt||i|dS(Ns;Can't set values on read-only fields (name=%s, class=%s.%s)( sselfsreadonlys TypeErrors__name__sobjects __class__s __module__ssetattrsvalue(sselfsobjectsvalue((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pyssets ,(s__name__s __module__sNones_typescontexts missing_valuesobjects_Field__missing_value_markersorders constraintsValidatedPropertysdefaultsTruesFalses__init__sbindsvalidates__eq__s__ne__s _validatesgetsquerysset(((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pysField,s   !5      s ContainercBstZdZRS(NcCs_tt|i|t|d o4yt|Wq[tj ot|q[XndS(Ns __contains__( ssupers Containersselfs _validatesvalueshasattrsiters TypeErrors NotAContainer(sselfsvalue((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys _validates (s__name__s __module__s _validate(((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys ContainerssIterablecBstZdZRS(NcCsJtt|i|yt|Wntj ot|nXdS(N(ssupersIterablesselfs _validatesvaluesiters TypeErrors NotAnIterator(sselfsvalue((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys _validates (s__name__s __module__s _validate(((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pysIterabless OrderablecBsAtZdZedZedZeeedZdZRS(sValues of ordered fields can be sorted. They can be restricted to a range of values. Orderable is a mixin used in combination with Field. sminsmaxcKsGt|_t|_tt|i|||_||_||_dS(N( sNonesselfsminsmaxssupers Orderables__init__skwsdefault(sselfsminsmaxsdefaultskw((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys__init__s     cCstt|i||itj o ||ijot||in|itj o ||ijot ||indS(N( ssupers Orderablesselfs _validatesvaluesminsNonesTooSmallsmaxsTooBig(sselfsvalue((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys _validates   ( s__name__s __module__s__doc__sValidatedPropertysminsmaxsNones__init__s _validate(((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys Orderables   s MinMaxLencBs2tZdZdZeZdedZdZRS(snExpresses constraints on the length of a field. MinMaxLen is a mixin used in combination with Field. icKs,||_||_tt|i|dS(N(s min_lengthsselfs max_lengthssupers MinMaxLens__init__skw(sselfs min_lengths max_lengthskw((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys__init__s  cCstt|i||itj ot||ijot||in|i tj ot||i jot ||i ndS(N( ssupers MinMaxLensselfs _validatesvalues min_lengthsNoneslensTooShorts max_lengthsTooLong(sselfsvalue((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys _validates &&(s__name__s __module__s__doc__s min_lengthsNones max_lengths__init__s _validate(((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys MinMaxLens sTextcBs0tZdZeZeedZdZRS(s1A field containing text used for human discourse.cOstt|i||dS(N(ssupersTextsselfs__init__sargsskw(sselfsargsskw((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys__init__scCs|i||SdS(s >>> t = Text(constraint=lambda v: 'x' in v) >>> t.fromUnicode("foo x spam") Traceback (most recent call last): ... WrongType: ('foo x spam', ) >>> t.fromUnicode(u"foo x spam") u'foo x spam' >>> t.fromUnicode(u"foo spam") Traceback (most recent call last): ... ConstraintNotSatisfied: foo spam N(sselfsvalidatesstr(sselfsstr((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys fromUnicodes  ( s__name__s __module__s__doc__sunicodes_types implementss IFromUnicodes__init__s fromUnicode(((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pysText s   sTextLinecBstZdZdZRS(sA text field with no newlines.cCsd|jo d|jSdS(Ns s (svalue(sselfsvalue((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys constraint(s(s__name__s __module__s__doc__s constraint(((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pysTextLine%s sPasswordcBstZdZRS(s2A text field containing a text used as a password.(s__name__s __module__s__doc__(((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pysPassword+s sBoolcBsLtZdZeeZeedj odZdZndZRS(sA field representing a Bool.icCs4t|tot|}nti||dS(N(s isinstancesvaluesintsboolsFields _validatesself(sselfsvalue((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys _validate7scCs7t|tot|}nti|||dS(N(s isinstancesvaluesintsboolsFieldssetsselfsobject(sselfsobjectsvalue((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pysset>scCs.|djp |dj}|i||SdS(s >>> b = Bool() >>> b.fromUnicode('True') True >>> b.fromUnicode('') False >>> b.fromUnicode('true') True >>> b.fromUnicode('false') or b.fromUnicode('False') False sTruestrueN(sstrsvsselfsvalidate(sselfsstrsv((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys fromUnicodeCs  ( s__name__s __module__s__doc__stypesTrues_types _validatessets fromUnicode(((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pysBool.s    sIntcBs6tZdZeefZeedZdZ RS(s A field representing an Integer.cOstt|i||dS(N(ssupersIntsselfs__init__sargsskw(sselfsargsskw((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys__init__ZscCs!t|}|i||SdS(s >>> f = Int() >>> f.fromUnicode("125") 125 >>> f.fromUnicode("125.6") Traceback (most recent call last): ... ValueError: invalid literal for int(): 125.6 N(sintsstrsvsselfsvalidate(sselfsstrsv((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys fromUnicode]s   ( s__name__s __module__s__doc__sintslongs_types implementss IFromUnicodes__init__s fromUnicode(((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pysIntTs    N( s__doc__szope.interfaces Attributes providedBys implementss zope.schema._bootstrapinterfacessStopValidations IFromUnicodesRequiredMissings WrongTypesConstraintNotSatisfieds NotAContainers NotAnIteratorsTooSmallsTooBigsTooShortsTooLongs InvalidValueszope.schema._schemas getFieldssobjectsValidatedPropertysFields ContainersIterables Orderables MinMaxLensTextsTextLinesPasswordsBoolsInt(sTooLongs ContainersStopValidations NotAContainersFields IFromUnicodesBools OrderablesTooBigsRequiredMissingsConstraintNotSatisfieds NotAnIteratorsPasswordsValidatedPropertys WrongTypesTextLines providedBys getFieldss InvalidValues implementssTooShortsInts Attributes MinMaxLensTooSmallsTextsIterable((s:build/bdist.linux-i686/egg/zope/schema/_bootstrapfields.pys?s*       '&PK4׸YZ Z zope/schema/fieldproperty.pyc; ]53Dc@s)dZeZdefdYZdS(scComputed attributes based on schema fields $Id: fieldproperty.py 25177 2004-06-02 13:17:31Z jim $ s FieldPropertycBs5tZdZedZdZdZdZRS(s0Computed attributes based on schema fields Field properties provide default values, data validation and error messages based on data found in field meta-data. Note that FieldProperties cannot be used with slots. They can only be used for attributes stored in instance dictionaries. cCs0|tjo |i}n||_||_dS(N(snamesNonesfields__name__sselfs_FieldProperty__fields_FieldProperty__name(sselfsfieldsname((s7build/bdist.linux-i686/egg/zope/schema/fieldproperty.pys__init__s   cCs|tjo|Sn|ii|it}|tjoE|ii |}t |dt}|tjot |iqn|SdS(Nsdefault( sinstsNonesselfs__dict__sgets_FieldProperty__names_markersvalues_FieldProperty__fieldsbindsfieldsgetattrsAttributeError(sselfsinstsklasssvaluesfield((s7build/bdist.linux-i686/egg/zope/schema/fieldproperty.pys__get__%s   cCs3|ii|}|i|||i|i%scCs't|i}|i||SdS(sBReturn a list of (name, value) tuples in native schema order. N(s getFieldssschemasitemssfieldsssorts _fieldsorter(sschemas _fieldsortersfields((s1build/bdist.linux-i686/egg/zope/schema/_schema.pysgetFieldsInOrder$s cCs5gi}t|D]\}}||q~SdS(sFReturn a list of all the Field names in a schema in schema order. N(sappends_[1]sgetFieldsInOrdersschemasnamesfield(sschemas_[1]sfieldsname((s1build/bdist.linux-i686/egg/zope/schema/_schema.pysgetFieldNamesInOrder,sN(s__doc__s getFieldNamess getFieldssgetFieldsInOrdersgetFieldNamesInOrder(s getFieldss getFieldNamessgetFieldsInOrdersgetFieldNamesInOrder((s1build/bdist.linux-i686/egg/zope/schema/_schema.pys?s  PK4 y+p+pzope/schema/_field.pyc; ]53Dc@sdZdkZdkZdklZlZdklZdkl Z l Z l Z dk l Z lZdklZdklZlZlZdklZd klZd klZlZlZd klZlZlZlZd klZlZlZl Z l!Z!d kl"Z"l#Z#l$Z$dkl%Z%l&Z&l'Z'dkl(Z(dkl)Z)l*Z*dkl+Z+l,Z,l-Z-dkl.Z.l/Z/dkl0Z0l1Z1l2Z2dkl3Z3dkl4Z4dk5l6Z6l7Z7l8Z8l9Z9dk5l:Z:dk5l;Z;l<Z<l=Z=l>Z>l?Z?dk5l:Z:l@Z@dkAlBZBdkClDZDdkClEZElFZFeBede6_GeBede6_HeBede6_IeBed e6_Je e6eeBed!e:_KeBed"e:_Le e;ee e<ee e?e"e e=ee e>ed#e;fd$YZMd%e:e6fd&YZNd'eNfd(YZOd)eNfd*YZPd+e9e6fd,YZQd-e9e6fd.YZRd/e9e6fd0YZSd1e6fd2YZTd3e6fd4YZUeVd5ZWd6ZXd7e:e8e6fd8YZYd9eYfd:YZZd;eYfd<YZ[d=eYfd>YZeVd?Z\d@e6fdAYZ]dBe:e8e6fdCYZ^ei_dDi`ZadEePfdFYZbei_dGi`ZcdHePfdIYZddJePfdKYZedS(LsDSchema Fields $Id: _field.py 27056 2004-08-12 16:09:51Z srichter $ N(sdatetimesdate(sSet(sclassImplementss implementssdirectlyProvides(s IInterfacesIMethod(sIField(s IMinMaxLensITexts ITextLine(s ISourceText(sIInterfaceField(sIBytessIASCIIs IBytesLine(sIBoolsIIntsIFloats IDatetime(sIChoicesITuplesIListsISetsIDict(s IPasswordsIObjectsIDate(sIURIsIIds IFromUnicode(s IVocabulary(sValidationErrors InvalidValue(s WrongTypesWrongContainedTypes NotUnique(sSchemaNotProvidedsSchemaNotFullyImplemented(s InvalidURIs InvalidIdsInvalidDottedName(sConstraintNotSatisfied(sUnbound(sFields ContainersIterables Orderable(s MinMaxLen(sTextsTextLinesBoolsIntsPassword(s MinMaxLensValidatedProperty(s FieldProperty(sgetVocabularyRegistry(s SimpleTermsSimpleVocabularystitles descriptionsrequiredsreadonlys min_lengths max_lengths SourceTextcBs!tZeiZeeeZRS(N(s__name__s __module__s ISourceTexts__doc__s implementssunicodes_type(((s0build/bdist.linux-i686/egg/zope/schema/_field.pys SourceTextFs  sBytescBs-tZeiZeeeeZdZRS(NcCs!t|}|i||SdS(s >>> b = Bytes(constraint=lambda v: 'x' in v) >>> b.fromUnicode(u" foo x.y.z bat") ' foo x.y.z bat' >>> b.fromUnicode(u" foo y.z bat") Traceback (most recent call last): ... ConstraintNotSatisfied: foo y.z bat N(sstrsusvsselfsvalidate(sselfsusv((s0build/bdist.linux-i686/egg/zope/schema/_field.pys fromUnicodeQs   ( s__name__s __module__sIBytess__doc__s implementss IFromUnicodesstrs_types fromUnicode(((s0build/bdist.linux-i686/egg/zope/schema/_field.pysBytesKs  sASCIIcBs$tZeiZeedZRS(NcCsQtt|i|| odSnttt|dj o tndS(s >>> ascii = ASCII() Make sure we accept empty strings: >>> empty = '' >>> ascii._validate(empty) and all kinds of alphanumeric strings: >>> alphanumeric = "Bob's my 23rd uncle" >>> ascii._validate(alphanumeric) >>> umlauts = "Khlerstrae" >>> ascii._validate(umlauts) Traceback (most recent call last): ... InvalidValue Ni( ssupersASCIIsselfs _validatesvaluesmaxsmapsords InvalidValue(sselfsvalue((s0build/bdist.linux-i686/egg/zope/schema/_field.pys _validatees (s__name__s __module__sIASCIIs__doc__s implementss _validate(((s0build/bdist.linux-i686/egg/zope/schema/_field.pysASCIIas  s BytesLinecBs!tZdZeedZRS(sA Text field with no newlines.cCsd|jSdS(Ns (svalue(sselfsvalue((s0build/bdist.linux-i686/egg/zope/schema/_field.pys constraints(s__name__s __module__s__doc__s implementss IBytesLines constraint(((s0build/bdist.linux-i686/egg/zope/schema/_field.pys BytesLines  sFloatcBs6tZeiZeeeeZdZdZ RS(NcOstt|i||dS(N(ssupersFloatsselfs__init__sargsskw(sselfsargsskw((s0build/bdist.linux-i686/egg/zope/schema/_field.pys__init__scCs!t|}|i||SdS(s >>> f = Float() >>> f.fromUnicode("1.25") 1.25 >>> f.fromUnicode("1.25.6") Traceback (most recent call last): ... ValueError: invalid literal for float(): 1.25.6 N(sfloatsusvsselfsvalidate(sselfsusv((s0build/bdist.linux-i686/egg/zope/schema/_field.pys fromUnicodes   ( s__name__s __module__sIFloats__doc__s implementss IFromUnicodesfloats_types__init__s fromUnicode(((s0build/bdist.linux-i686/egg/zope/schema/_field.pysFloats    sDatetimecBs*tZeiZeeeZdZRS(NcOstt|i||dS(N(ssupersDatetimesselfs__init__sargsskw(sselfsargsskw((s0build/bdist.linux-i686/egg/zope/schema/_field.pys__init__s(s__name__s __module__s IDatetimes__doc__s implementssdatetimes_types__init__(((s0build/bdist.linux-i686/egg/zope/schema/_field.pysDatetimes  sDatecBs!tZeiZeeeZRS(N(s__name__s __module__sIDates__doc__s implementssdates_type(((s0build/bdist.linux-i686/egg/zope/schema/_field.pysDates  sChoicecBsBtZdZeeeedZdZdZdZ RS(ssChoice fields can have a value found in a constant or dynamic set of values given by the field definition. cKs|tjo |tj p td|tjp |tjp tdt|_t|_|tj oti||_nDt|t t fo ||_n!t i |pt||_t |i|_tt|i|t|_dS(sInitialize object.s-You must specify either values or vocabulary.s.You cannot specify both values and vocabulary.N(svaluessNones vocabularysAssertionErrorsselfsvocabularyNamesSimpleVocabularys fromValuess isinstancesunicodesstrs IVocabularys providedBysbools _init_fieldssupersChoices__init__skwsFalse(sselfsvaluess vocabularyskw((s0build/bdist.linux-i686/egg/zope/schema/_field.pys__init__s%$     cCsett|i|}|itjo |itj o%t }|i ||i|_n|SdS(s,See zope.schema._bootstrapinterfaces.IField.N( ssupersChoicesselfsbindsobjectsclones vocabularysNonesvocabularyNamesgetVocabularyRegistrysvrsget(sselfsobjectsvrsclone((s0build/bdist.linux-i686/egg/zope/schema/_field.pysbinds   cCs|i||SdS(sL >>> from vocabulary import SimpleVocabulary >>> t = Choice( ... vocabulary=SimpleVocabulary.fromValues([u'foo',u'bar'])) >>> t.fromUnicode(u"baz") Traceback (most recent call last): ... ConstraintNotSatisfied: baz >>> t.fromUnicode(u"foo") u'foo' N(sselfsvalidatesstr(sselfsstr((s0build/bdist.linux-i686/egg/zope/schema/_field.pys fromUnicodes  cCs|iodSntt|i||i}|tjoHt}y|i t|i }Wqt j ot dqXn||jo t|ndS(Ns'Can't validate value without vocabulary(sselfs _init_fieldssupersChoices _validatesvalues vocabularysNonesgetVocabularyRegistrysvrsgetsvocabularyNamesVocabularyRegistryErrors ValueErrorsConstraintNotSatisfied(sselfsvalues vocabularysvr((s0build/bdist.linux-i686/egg/zope/schema/_field.pys _validates     ( s__name__s __module__s__doc__s implementssIChoicesNones__init__sbinds fromUnicodes _validate(((s0build/bdist.linux-i686/egg/zope/schema/_field.pysChoices   sInterfaceFieldcBs$tZeiZeedZRS(NcCs5tt|i|ti| o tndS(N(ssupersInterfaceFieldsselfs _validatesvalues IInterfaces providedBys WrongType(sselfsvalue((s0build/bdist.linux-i686/egg/zope/schema/_field.pys _validates(s__name__s __module__sIInterfaceFields__doc__s implementss _validate(((s0build/bdist.linux-i686/egg/zope/schema/_field.pysInterfaceFields  cCs{|tjo g}n|tjo|SnxD|D]<}y|i|Wq3tj o}|i|q3Xq3W|SdS(sValidates a sequence value. Returns a list of validation errors generated during the validation. If no errors are generated, returns an empty list. value_type is a field. value is the sequence being validated. errors is an optional list of errors that will be prepended to the return value. To illustrate, we'll use a text value type. All values must be unicode. >>> field = TextLine(required=True) To validate a sequence of various values: >>> errors = _validate_sequence(field, ('foo', u'bar', 1)) >>> errors [foo , 1 ] The only valid value in the sequence is the second item. The others generated errors. We can use the optional errors argument to collect additional errors for a new sequence: >>> errors = _validate_sequence(field, (2, u'baz'), errors) >>> errors [foo , 1 , 2 ] N( serrorssNones value_typesvaluesitemsvalidatesValidationErrorserrorsappend(s value_typesvalueserrorssitemserror((s0build/bdist.linux-i686/egg/zope/schema/_field.pys_validate_sequences   cCsBg}x5|D]-}||jo t|n|i|q WdS(N(s temp_valuessvaluesitems NotUniquesappend(svalues temp_valuessitem((s0build/bdist.linux-i686/egg/zope/schema/_field.pys_validate_uniqueness$s   sAbstractCollectioncBs5tZeZeZeedZdZdZRS(NcKsWtt|i||tj oti| o t dn||_||_ dS(Ns$'value_type' must be field instance.( ssupersAbstractCollectionsselfs__init__skws value_typesNonesIFields providedBys ValueErrorsunique(sselfs value_typesuniqueskw((s0build/bdist.linux-i686/egg/zope/schema/_field.pys__init__0s   cCsItt|i|}|itj o|ii||_n|SdS(s,See zope.schema._bootstrapinterfaces.IField.N(ssupersAbstractCollectionsselfsbindsobjectsclones value_typesNone(sselfsobjectsclone((s0build/bdist.linux-i686/egg/zope/schema/_field.pysbind8s cCsXtt|i|t|i|}|o t|n|i ot |ndS(N( ssupersAbstractCollectionsselfs _validatesvalues_validate_sequences value_typeserrorssWrongContainedTypesuniques_validate_uniqueness(sselfsvalueserrors((s0build/bdist.linux-i686/egg/zope/schema/_field.pys _validateAs   ( s__name__s __module__sNones value_typesFalsesuniques__init__sbinds _validate(((s0build/bdist.linux-i686/egg/zope/schema/_field.pysAbstractCollection,s  sTuplecBstZdZeeeZRS(sA field representing a Tuple.(s__name__s __module__s__doc__s implementssITuplestuples_type(((s0build/bdist.linux-i686/egg/zope/schema/_field.pysTupleIs  sListcBstZdZeeeZRS(sA field representing a List.(s__name__s __module__s__doc__s implementssIListslists_type(((s0build/bdist.linux-i686/egg/zope/schema/_field.pysListNs  sSetcBs'tZdZeeeZdZRS(sA field representing a set.cKs=d|jotdntt|idt|dS(Nsuniques6__init__() got an unexpected keyword argument 'unique'(skws TypeErrorssupersSetsselfs__init__sTrue(sselfskw((s0build/bdist.linux-i686/egg/zope/schema/_field.pys__init__Ws (s__name__s __module__s__doc__s implementssISetsSetTypes_types__init__(((s0build/bdist.linux-i686/egg/zope/schema/_field.pysSetSs  cCs|tjo g}nx|idtD]}ti|| oy8||}t i|o|i t ||nWqt j o}|i|qtj o}|itqXq*q*W|SdS(Nsall(serrorssNonesschemasnamessTruesnamesIMethods providedBys attributesIFieldsvalidatesgetattrsvaluesValidationErrorserrorsappendsAttributeErrorsSchemaNotFullyImplemented(sschemasvalueserrorssnameserrors attribute((s0build/bdist.linux-i686/egg/zope/schema/_field.pys_validate_fields]s   sObjectcBs-tZeiZeedZdZRS(NcKs>ti| o tn||_tt|i|dS(N( s IInterfaces providedBysschemas WrongTypesselfssupersObjects__init__skw(sselfsschemaskw((s0build/bdist.linux-i686/egg/zope/schema/_field.pys__init__ss  cCsatt|i||ii| o tnt|i|}|ot |ndS(N( ssupersObjectsselfs _validatesvaluesschemas providedBysSchemaNotProvideds_validate_fieldsserrorssWrongContainedType(sselfsvalueserrors((s0build/bdist.linux-i686/egg/zope/schema/_field.pys _validatezs  (s__name__s __module__sIObjects__doc__s implementss__init__s _validate(((s0build/bdist.linux-i686/egg/zope/schema/_field.pysObjectos   sDictcBsBtZdZeeeZeZeZ eedZ dZ RS(sA field representing a Dict.cKstt|i||tj oti| o t dn|tj oti| o t dn||_||_ dS(Ns"'key_type' must be field instance.s$'value_type' must be field instance.( ssupersDictsselfs__init__skwskey_typesNonesIFields providedBys ValueErrors value_type(sselfskey_types value_typeskw((s0build/bdist.linux-i686/egg/zope/schema/_field.pys__init__s   cCstt|i|g}zV|iot|i|i|}nt|i ||}|o t |nWdt }XdS(N( ssupersDictsselfs _validatesvalueserrorss value_types_validate_sequencesvaluesskey_typesWrongContainedTypesNone(sselfsvalueserrors((s0build/bdist.linux-i686/egg/zope/schema/_field.pys _validates  ( s__name__s __module__s__doc__s implementssIDictsdicts_typesNoneskey_types value_types__init__s _validate(((s0build/bdist.linux-i686/egg/zope/schema/_field.pysDicts   s[a-zA-z0-9+.-]+:\S*$sURIcBs-tZdZeeedZdZRS(sURI schema field cCs8tt|i|t|odSnt|dS(s  >>> uri = URI(__name__='test') >>> uri.validate("http://www.python.org/foo/bar") >>> uri.validate("DAV:") >>> uri.validate("www.python.org/foo/bar") Traceback (most recent call last): ... InvalidURI: www.python.org/foo/bar N(ssupersURIsselfs _validatesvalues_isuris InvalidURI(sselfsvalue((s0build/bdist.linux-i686/egg/zope/schema/_field.pys _validates  cCs't|i}|i||SdS(s >>> uri = URI(__name__='test') >>> uri.fromUnicode("http://www.python.org/foo/bar") 'http://www.python.org/foo/bar' >>> uri.fromUnicode(" http://www.python.org/foo/bar") 'http://www.python.org/foo/bar' >>> uri.fromUnicode(" \n http://www.python.org/foo/bar\n") 'http://www.python.org/foo/bar' >>> uri.fromUnicode("http://www.python.org/ foo/bar") Traceback (most recent call last): ... InvalidURI: http://www.python.org/ foo/bar N(sstrsvaluesstripsvsselfsvalidate(sselfsvaluesv((s0build/bdist.linux-i686/egg/zope/schema/_field.pys fromUnicodes  (s__name__s __module__s__doc__s implementssIURIs IFromUnicodes _validates fromUnicode(((s0build/bdist.linux-i686/egg/zope/schema/_field.pysURIs   s3([a-zA-Z][a-zA-z0-9_]*)([.][a-zA-Z][a-zA-z0-9_]*)*$sIdcBs-tZdZeeedZdZRS(sKId field Values of id fields must be either uris or dotted names. cCsZtt|i|t|odSnt|o d|jodSnt|dS(s >>> id = Id(__name__='test') >>> id.validate("http://www.python.org/foo/bar") >>> id.validate("zope.app.content") >>> id.validate("zope.app.content/a") Traceback (most recent call last): ... InvalidId: zope.app.content/a >>> id.validate("http://zope.app.content x y") Traceback (most recent call last): ... InvalidId: http://zope.app.content x y Ns.(ssupersIdsselfs _validatesvalues_isuris _isdotteds InvalidId(sselfsvalue((s0build/bdist.linux-i686/egg/zope/schema/_field.pys _validates  cCs't|i}|i||SdS(s >>> id = Id(__name__='test') >>> id.fromUnicode("http://www.python.org/foo/bar") 'http://www.python.org/foo/bar' >>> id.fromUnicode(u" http://www.python.org/foo/bar ") 'http://www.python.org/foo/bar' >>> id.fromUnicode("http://www.python.org/ foo/bar") Traceback (most recent call last): ... InvalidId: http://www.python.org/ foo/bar >>> id.fromUnicode(" \n x.y.z \n") 'x.y.z' N(sstrsvaluesstripsvsselfsvalidate(sselfsvaluesv((s0build/bdist.linux-i686/egg/zope/schema/_field.pys fromUnicodes (s__name__s __module__s__doc__s implementssIIds IFromUnicodes _validates fromUnicode(((s0build/bdist.linux-i686/egg/zope/schema/_field.pysIds   s DottedNamecBs)tZdZdZdZdZRS(s[Dotted name field. Values of DottedName fields must be Python-style dotted names. cOst|idd|_|idjotdn|idt|_|itj o9t|i|_|i|ijotdqntt |i ||dS(s >>> DottedName(min_dots=-1) Traceback (most recent call last): ... ValueError: min_dots cannot be less than zero >>> DottedName(max_dots=-1) Traceback (most recent call last): ... ValueError: max_dots cannot be less than min_dots >>> DottedName(max_dots=1, min_dots=2) Traceback (most recent call last): ... ValueError: max_dots cannot be less than min_dots >>> dotted_name = DottedName(max_dots=1, min_dots=1) >>> dotted_name = DottedName(max_dots=1) >>> dotted_name.min_dots 0 >>> dotted_name = DottedName(min_dots=1) >>> dotted_name.max_dots >>> dotted_name.min_dots 1 smin_dotsis!min_dots cannot be less than zerosmax_dotss%max_dots cannot be less than min_dotsN( sintskwspopsselfsmin_dotss ValueErrorsNonesmax_dotsssupers DottedNames__init__sargs(sselfsargsskw((s0build/bdist.linux-i686/egg/zope/schema/_field.pys__init__scCstt|i|t| ot|n|id}||i jotd|i |fn|i t j o ||i jotd|i |fndS(s >>> dotted_name = DottedName(__name__='test') >>> dotted_name.validate("a.b.c") >>> dotted_name.validate("a") >>> dotted_name.validate(" a ") Traceback (most recent call last): ... InvalidDottedName: a >>> dotted_name = DottedName(__name__='test', min_dots=1) >>> dotted_name.validate('a.b') >>> dotted_name.validate('a.b.c.d') >>> dotted_name.validate('a') Traceback (most recent call last): ... InvalidDottedName: ('too few dots; 1 required', 'a') >>> dotted_name = DottedName(__name__='test', max_dots=0) >>> dotted_name.validate('a') >>> dotted_name.validate('a.b') Traceback (most recent call last): ... InvalidDottedName: ('too many dots; no more than 0 allowed', 'a.b') >>> dotted_name = DottedName(__name__='test', max_dots=2) >>> dotted_name.validate('a') >>> dotted_name.validate('a.b') >>> dotted_name.validate('a.b.c') >>> dotted_name.validate('a.b.c.d') Traceback (most recent call last): ... InvalidDottedName: ('too many dots; no more than 2 allowed', 'a.b.c.d') >>> dotted_name = DottedName(__name__='test', max_dots=1, min_dots=1) >>> dotted_name.validate('a.b') >>> dotted_name.validate('a') Traceback (most recent call last): ... InvalidDottedName: ('too few dots; 1 required', 'a') >>> dotted_name.validate('a.b.c') Traceback (most recent call last): ... InvalidDottedName: ('too many dots; no more than 1 allowed', 'a.b.c') s.stoo few dots; %d requireds&too many dots; no more than %d allowedN( ssupers DottedNamesselfs _validatesvalues _isdottedsInvalidDottedNamescountsdotssmin_dotssmax_dotssNone(sselfsvaluesdots((s0build/bdist.linux-i686/egg/zope/schema/_field.pys _validate:s- cCs't|i}|i||SdS(N(sstrsvaluesstripsvsselfsvalidate(sselfsvaluesv((s0build/bdist.linux-i686/egg/zope/schema/_field.pys fromUnicodets (s__name__s __module__s__doc__s__init__s _validates fromUnicode(((s0build/bdist.linux-i686/egg/zope/schema/_field.pys DottedNames  & :(fs__doc__swarningssresdatetimesdatessetssSetsSetTypeszope.interfacesclassImplementss implementssdirectlyProvidesszope.interface.interfacess IInterfacesIMethodszope.schema.interfacessIFields IMinMaxLensITexts ITextLines ISourceTextsIInterfaceFieldsIBytessIASCIIs IBytesLinesIBoolsIIntsIFloats IDatetimesIChoicesITuplesIListsISetsIDicts IPasswordsIObjectsIDatesIURIsIIds IFromUnicodes IVocabularysValidationErrors InvalidValues WrongTypesWrongContainedTypes NotUniquesSchemaNotProvidedsSchemaNotFullyImplementeds InvalidURIs InvalidIdsInvalidDottedNamesConstraintNotSatisfiedsUnboundszope.schema._bootstrapfieldssFields ContainersIterables Orderables MinMaxLensTextsTextLinesBoolsIntsPasswordsValidatedPropertyszope.schema.fieldpropertys FieldPropertyszope.schema.vocabularysgetVocabularyRegistrys SimpleTermsSimpleVocabularystitles descriptionsrequiredsreadonlys min_lengths max_lengths SourceTextsBytessASCIIs BytesLinesFloatsDatetimesDatesChoicesInterfaceFieldsNones_validate_sequences_validate_uniquenesssAbstractCollectionsTuplesLists_validate_fieldssObjectsDictscompilesmatchs_isurisURIs _isdottedsIds DottedName(UsSchemaNotFullyImplementedsIFloats InvalidValues_validate_sequencesdatetimesChoicesIDates InvalidURIs WrongTypesBytessURIs InvalidIdsWrongContainedTypes ISourceTextsIURIsDatetimes_validate_uniquenesssASCIIsSimpleVocabularysISets SimpleTerms _isdotteds SourceTextsITexts MinMaxLensITuplesConstraintNotSatisfieds NotUniquesres FieldPropertysIInts_validate_fieldssIDictsIListsTextLinesclassImplementssValidatedPropertys IPasswords IInterfacesIterablesObjectsIInterfaceFieldsBools ContainersIBools_isuris ITextLinesTuplesIObjectsDates IVocabularysSetTypesdirectlyProvidessSetsIIdsIntsTextsUnboundsFields IFromUnicodesDicts OrderablesInterfaceFieldsValidationErrors IBytesLinesAbstractCollectionsIChoicesIFields IMinMaxLensPasswordswarningss DottedNamesListsInvalidDottedNamesIASCIIs BytesLinesdates implementss IDatetimesSchemaNotProvidedsgetVocabularyRegistrysIMethodsFloatsIBytessId((s0build/bdist.linux-i686/egg/zope/schema/_field.pys?s      %    %         F )  !*2PK4&ll$zope/schema/_bootstrapinterfaces.pyc; ]53Dc@sVdZdkZdklZedZdefdYZdeii fdYZ de fd YZ d e fd YZ d e fd YZ de fdYZde fdYZde fdYZde fdYZde fdYZde fdYZde fdYZdeiifdYZdS(sjBootstrap schema interfaces and exceptions $Id: _bootstrapinterfaces.py 25177 2004-06-02 13:17:31Z jim $ N(sMessageIDFactoryszopesStopValidationcBstZdZRS(sRaised if the validation is completed early. Note that this exception should be always caught, since it is just a way for the validator to save time. (s__name__s __module__s__doc__(((s>build/bdist.linux-i686/egg/zope/schema/_bootstrapinterfaces.pysStopValidations sValidationErrorcBs)tZdZdZdZdZRS(s'Raised if the Validation process fails.cCs|iiSdS(N(sselfs __class__s__doc__(sself((s>build/bdist.linux-i686/egg/zope/schema/_bootstrapinterfaces.pysdoc!scCst|i|iSdS(N(scmpsselfsargssother(sselfsother((s>build/bdist.linux-i686/egg/zope/schema/_bootstrapinterfaces.pys__cmp__$scCsditt|iSdS(Ns (sjoinsmapsstrsselfsargs(sself((s>build/bdist.linux-i686/egg/zope/schema/_bootstrapinterfaces.pys__repr__'s(s__name__s __module__s__doc__sdocs__cmp__s__repr__(((s>build/bdist.linux-i686/egg/zope/schema/_bootstrapinterfaces.pysValidationErrors   sRequiredMissingcBstZedZRS(NsRequired input is missing.(s__name__s __module__s_s__doc__(((s>build/bdist.linux-i686/egg/zope/schema/_bootstrapinterfaces.pysRequiredMissing*ss WrongTypecBstZedZRS(NsObject is of wrong type.(s__name__s __module__s_s__doc__(((s>build/bdist.linux-i686/egg/zope/schema/_bootstrapinterfaces.pys WrongType-ssTooBigcBstZedZRS(NsValue is too big(s__name__s __module__s_s__doc__(((s>build/bdist.linux-i686/egg/zope/schema/_bootstrapinterfaces.pysTooBig0ssTooSmallcBstZedZRS(NsValue is too small(s__name__s __module__s_s__doc__(((s>build/bdist.linux-i686/egg/zope/schema/_bootstrapinterfaces.pysTooSmall3ssTooLongcBstZedZRS(NsValue is too long(s__name__s __module__s_s__doc__(((s>build/bdist.linux-i686/egg/zope/schema/_bootstrapinterfaces.pysTooLong6ssTooShortcBstZedZRS(NsValue is too short(s__name__s __module__s_s__doc__(((s>build/bdist.linux-i686/egg/zope/schema/_bootstrapinterfaces.pysTooShort9ss InvalidValuecBstZedZRS(Ns Invalid value(s__name__s __module__s_s__doc__(((s>build/bdist.linux-i686/egg/zope/schema/_bootstrapinterfaces.pys InvalidValue<ssConstraintNotSatisfiedcBstZedZRS(NsConstraint not satisfied(s__name__s __module__s_s__doc__(((s>build/bdist.linux-i686/egg/zope/schema/_bootstrapinterfaces.pysConstraintNotSatisfied?ss NotAContainercBstZedZRS(NsNot a container(s__name__s __module__s_s__doc__(((s>build/bdist.linux-i686/egg/zope/schema/_bootstrapinterfaces.pys NotAContainerBss NotAnIteratorcBstZedZRS(NsNot an iterator(s__name__s __module__s_s__doc__(((s>build/bdist.linux-i686/egg/zope/schema/_bootstrapinterfaces.pys NotAnIteratorEss IFromUnicodecBstZdZdZRS(sParse a unicode string to a value We will often adapt fields to this interface to support views and other applications that need to conver raw data as unicode values. cCsdS(s-Convert a unicode string to a value. N((sstr((s>build/bdist.linux-i686/egg/zope/schema/_bootstrapinterfaces.pys fromUnicodeRs(s__name__s __module__s__doc__s fromUnicode(((s>build/bdist.linux-i686/egg/zope/schema/_bootstrapinterfaces.pys IFromUnicodeIs (s__doc__szope.interfaceszopeszope.i18nmessageidsMessageIDFactorys_s ExceptionsStopValidations interfacesInvalidsValidationErrorsRequiredMissings WrongTypesTooBigsTooSmallsTooLongsTooShorts InvalidValuesConstraintNotSatisfieds NotAContainers NotAnIterators Interfaces IFromUnicode(sTooLongsTooShortsRequiredMissingsValidationErrorsStopValidationsConstraintNotSatisfieds WrongTypes NotAnIterators NotAContainers IFromUnicodesTooSmallsMessageIDFactoryszopes InvalidValuesTooBigs_((s>build/bdist.linux-i686/egg/zope/schema/_bootstrapinterfaces.pys?s     PK4=:WmWmzope/schema/interfaces.pyc; ]53Dc@s7dZdklZlZdklZlZlZlZl Z dkl Z l Z dk l Z e dZdklZlZdklZdklZlZd klZd klZlZd klZlZd klZlZd klZdefdYZdefdYZdefdYZdefdYZ defdYZ!defdYZ"defdYZ#de$fdYZ%defdYZ&d e&fd!YZ'd"e&fd#YZ(d$e&fd%YZ)d&e&fd'YZ*d(e)fd)YZ+d*e*fd+YZ,d,e&fd-YZ-d.e&fd/YZ.d0e,e'e&fd1YZ/d2e/fd3YZ0d4e/fd5YZ1d6e,e'e&fd7YZ2d8e2fd9YZ3d:e2fd;YZ4d<e4fd=YZ5d>e+e&fd?YZ6d@e+e&fdAYZ7dBe+e&fdCYZ8dDe+e&fdEYZ9dFZ:dGZ;dHe1fdIYZ<dJe1fdKYZ=dLe&fdMYZ>dNe,e'e(fdOYZ?dPe?fdQYZ@dRe?fdSYZAdTe@fdUYZBdVe@fdWYZCdXeAfdYYZDdZe&fd[YZEd\e,e'e(fd]YZFd^efd_YZGd`eGfdaYZHdbeHfdcYZIddefdeYZJdfefdgYZKdheKeJfdiYZLdjeLfdkYZMdlefdmYZNdnS(osYSchema interfaces and exceptions $Id: interfaces.py 28315 2004-11-01 23:30:26Z fdrake $ (s Interfaces Attribute(sFieldsTextsTextLinesBoolsInt(s ContainersIterable(sMessageIDFactoryszope(sStopValidationsValidationError(s IFromUnicode(sRequiredMissings WrongType(sConstraintNotSatisfied(s NotAContainers NotAnIterator(sTooSmallsTooBig(sTooShortsTooLong(s InvalidValuesWrongContainedTypecBstZedZRS(NsWrong contained type(s__name__s __module__s_s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysWrongContainedType%ss NotUniquecBstZedZRS(Ns/One or more entries of sequence are not unique.(s__name__s __module__s_s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys NotUnique(ssSchemaNotFullyImplementedcBstZedZRS(NsSchema not fully implemented(s__name__s __module__s_s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysSchemaNotFullyImplemented+ssSchemaNotProvidedcBstZedZRS(NsSchema not provided(s__name__s __module__s_s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysSchemaNotProvided.ss InvalidURIcBstZedZRS(NsThe specified URI is not valid.(s__name__s __module__s_s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys InvalidURI1ss InvalidIdcBstZedZRS(NsThe specified id is not valid.(s__name__s __module__s_s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys InvalidId4ssInvalidDottedNamecBstZedZRS(Ns'The specified dotted name is not valid.(s__name__s __module__s_s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysInvalidDottedName7ssUnboundcBstZedZRS(NsThe field is not bound.(s__name__s __module__s_s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysUnbound:ssIFieldc BsdtZdZdZededdeddddeZeded ded dddeZ e ded ded de Z e ded deddedeZ ededdedZededdedZededdedde de ZdZdZdZedZdZRS(sBasic Schema Field Interface. Fields are used for Interface specifications. They at least provide a title, description and a default value. You can also specify if they are required and/or readonly. The Field Interface is also used for validation and specifying constraints. We want to make it possible for a IField to not only work on its value but also on the object this value is bound to. This enables a Field implementation to perform validation against an object which also marks a certain place. Note that many fields need information about the object containing a field. For example, when validating a value to be set as an object attribute, it may be necessary for the field to introspect the object's state. This means that the field needs to have access to the object when performing validation:: bound = field.bind(object) bound.validate(value) cCsdS(sReturn a copy of this field which is bound to context. The copy of the Field will have the 'context' attribute set to 'object'. This way a Field can implement more complex checks involving the object's location/environment. Many fields don't need to be bound. Only fields that condition validation or properties on an object containing the field need to be bound. N((sobject((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysbindWs stitleuTitles descriptionuA short summary or labelsdefaultusrequiredu DescriptionuA description of the fielduRequiredu2Tells whether a field requires its value to exist.u Read Onlyu-If true, the field's value cannot be changed.u Default ValueuRThe field default value may be None or a legal field valueu Missing ValueujIf input for this Field is missing, and that's ok, then this is the value to useu Field Orderu! The order attribute can be used to determine the order in which fields in a schema were defined. If one field is created after another (in the same thread), its order will be greater. (Fields in separate threads could have the same order.) sreadonlycCsdS(u9Check a customized constraint on the value. You can implement this method with your Field to require a certain constraint. This relaxes the need to inherit/subclass a Field you to add a simple constraint. Returns true if the given value is within the Field's constraint. N((svalue((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys constraintscCsdS(uValidate that the given value is a valid field value. Returns nothing but raises an error if the value is invalid. It checks everything specific to a Field and also checks with the additional constraint. N((svalue((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysvalidatescCsdS(s0Get the value of the field for the given object.N((sobject((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysgetscCsdS(suQuery the value of the field for the given object. Return the default if the value hasn't been set. N((sobjectsdefault((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysqueryscCsdS(srSet the value of the field for the object Raises a type error if the field is a read-only field. N((sobjectsvalue((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pyssets(s__name__s __module__s__doc__sbindsTextLines_sFalsestitlesTexts descriptionsBoolsTruesrequiredsreadonlysFieldsdefaults missing_valuesIntsorders constraintsvalidatesgetsNonesquerysset(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIField=s<               s IIterablecBstZdZRS(uFields with a value that can be iterated over. The value needs to support iteration; the implementation mechanism is not constrained. (Either __iter__() or __getitem__() may be used.) (s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys IIterables s IContainercBstZdZRS(uFields whose value allows an 'x in value' check. The Value needs to support the 'in' operator, but is not constrained in how it does so (whether it defines __contains__() or __getitem__() is immaterial). (s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys IContainers s IOrderablecBstZdZRS(uField requiring its value to be orderable. The set of value needs support a complete ordering; the implementation mechanism is not constrained. Either __cmp__() or 'rich comparison' methods may be used. (s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys IOrderables sILencBstZdZRS(unA Field requiring its value to have a length. The value needs to have a conventional __len__ method. (s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysILens sIMinMaxcBsPtZdZededdedeZededdedeZRS(uField requiring its value to be between min and max. This implies that the value needs to support the IOrderable interface. stitleuStart of the rangesrequiredsdefaultu-End of the range (excluding the value itself)( s__name__s __module__s__doc__sFields_sFalsesNonesminsmax(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIMinMaxs  s IMinMaxLenc BsttZdZededdeddeddddZeded ded dedddeZRS( u<Field requiring the length of its value to be within a rangestitleuMinimum lengths descriptionu Value after whitespace processing cannot have less than min_length characters (if a string type) or elements (if another sequence type). If min_length is None, there is no minimum. srequiredsminisdefaultuMaximum lengthu Value after whitespace processing cannot have greater or equal than max_length characters (if a string type) or elements (if another sequence type). If max_length is None, there is no maximum.( s__name__s __module__s__doc__sInts_sFalses min_lengthsNones max_length(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys IMinMaxLens    sIInterfaceFieldcBstZdZRS(uUFields with a value that is an interface (implementing zope.interface.Interface).(s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIInterfaceFields sIBoolcBs/tZdZededdedZRS(uBoolean Field.stitleu Default Values descriptionuRThe field default value may be None or a legal field value(s__name__s __module__s__doc__sBools_sdefault(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIBools sIBytescBstZdZRS(uxField containing a byte string (like the python str). The value might be constrained to be with length limits. (s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIBytess sIASCIIcBstZdZRS(uField containing a 7-bit ASCII string. No characters > DEL (chr(127)) are allowed The value might be constrained to be with length limits. (s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIASCIIs s IBytesLinecBstZdZRS(u0Field containing a byte string without newlines.(s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys IBytesLines sITextcBstZdZRS(u"Field containing a unicode string.(s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysITexts s ISourceTextcBstZdZRS(u Field for source text of object.(s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys ISourceText"s s ITextLinecBstZdZRS(u3Field containing a unicode string without newlines.(s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys ITextLine%s s IPasswordcBstZdZRS(uFField containing a unicode string without newlines that is a password.(s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys IPassword(s sIIntcBsqtZdZededdedeZededdedeZededdedZ RS( u"Field containing an Integer Value.stitleuStart of the rangesrequiredsdefaultu-End of the range (excluding the value itself)u Default Values descriptionuRThe field default value may be None or a legal field value( s__name__s __module__s__doc__sInts_sFalsesNonesminsmaxsdefault(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIInt+s   sIFloatcBstZdZRS(uField containing a Float.(s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIFloat@s s IDatetimecBstZdZRS(uField containing a DateTime.(s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys IDatetimeCs sIDatecBstZdZRS(uField containing a date.(s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIDateFs cCs!ti| otSntSdS(N(sIFields providedBysvaluesFalsesTrue(svalue((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys _is_fieldIscCs/x$|D]}t| otSqqWtSdS(N(svaluessvalues _is_fieldsFalsesTrue(svaluessvalue((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys_fieldsNs  sIURIcBstZdZRS(s'A field containing an absolute URI (s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIURIUs sIIdcBstZdZRS(sA field containing a unique identifier A unique identifier is either an absolute URI or a dotted name. If it's a dotted name, it should have a module/package name as a prefix. (s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIIdYs sIChoicec Bs>tZdZedddddedeZeddZRS( uField whose value is contained in a predefined set Only one, values or vocabulary, may be specified for a given choice. stitleuVocabulary Names descriptionusThe name of the vocabulary to be used. This name is intended to be used by the IVocabularyRegistry's get() method.srequiredsdefaults vocabularysIBaseVocabulary to be used, or None. If None, the vocabularyName should be used by an IVocabularyRegistry should be used to locate an appropriate IBaseVocabulary object.( s__name__s __module__s__doc__sTextLinesFalsesNonesvocabularyNames Attributes vocabulary(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIChoice`s   s ICollectioncBsVtZdZededdedZededdeddeZRS(u|Abstract interface containing a collection value. The Value must be iterable and may have a min_length/max_length. stitles Value Types descriptionuHField value items must conform to the given type, expressed via a Field.sUnique Memberss?Specifies whether the members of the collection must be unique.sdefault( s__name__s __module__s__doc__sFields_s value_typesBoolsFalsesunique(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys ICollectionys  s ISequencecBstZdZRS(u7Abstract interface specifying that the value is ordered(s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys ISequences sIUnorderedCollectioncBstZdZRS(u>Abstract interface specifying that the value cannot be ordered(s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIUnorderedCollections sITuplecBstZdZRS(uUField containing a value that implements the API of a conventional Python tuple.(s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysITuples sIListcBstZdZRS(uTField containing a value that implements the API of a conventional Python list.(s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysILists sISetcBstZdZedZRS(uiField containing a value that implements the API of a conventional Python standard library sets.Set.u1This ICollection interface attribute must be True(s__name__s __module__s__doc__s Attributesunique(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysISets sIObjectcBs#tZdZededZRS(u!Field containing an Object value.sschemau<The Interface that defines the Fields comprising the Object.(s__name__s __module__s__doc__s Attributes_sschema(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIObjects sIDictcBs8tZdZededZededZRS(uField containing a conventional dict. The key_type and value_type fields allow specification of restrictions for keys and values contained in the dict. skey_typeuUField keys must conform to the given type, expressed via a Field. s value_typeuWField values must conform to the given type, expressed via a Field. (s__name__s __module__s__doc__s Attributes_skey_types value_type(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIDicts sITermcBstZdZeddZRS(s3Object representing a single value in a vocabulary.svalues7The value used to represent vocabulary term in a field.(s__name__s __module__s__doc__s Attributesvalue(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysITerms sITokenizedTermcBstZdZeddZRS(sBObject representing a single value in a tokenized vocabulary. stokensToken which can be used to represent the value on a stream. The value of this attribute must be a non-empty 7-bit string. Control characters are not allowed. (s__name__s __module__s__doc__s Attributestoken(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysITokenizedTerms sITitledTokenizedTermcBs#tZdZededZRS(s'A tokenized term that includes a title.stitleuTitle(s__name__s __module__s__doc__sTextLines_stitle(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysITitledTokenizedTerms sIBaseVocabularycBs tZdZdZdZRS(s(Representation of a vocabulary. At this most basic level, a vocabulary only need to support a test for containment. This can be implemented either by __contains__() or by sequence __getitem__() (the later only being useful for vocabularies which are intrinsically ordered). cCsdS(s:Returns True if the value is available in this vocabulary.N((svalue((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys __contains__scCsdS(sReturn the ITerm object for the term 'value'. If 'value' is not a valid term, this method raises LookupError. N((svalue((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysgetTerms(s__name__s __module__s__doc__s __contains__sgetTerm(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIBaseVocabularys  sIIterableVocabularycBs tZdZdZdZRS(sVocabulary which supports iteration over allowed values. The objects iteration provides must conform to the ITerm interface. cCsdS(s@Return an iterator which provides the terms from the vocabulary.N((((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys__iter__scCsdS(s0Return the number of valid terms, or sys.maxint.N((((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys__len__s(s__name__s __module__s__doc__s__iter__s__len__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIIterableVocabularys  s IVocabularycBstZdZRS(sVocabulary which is iterable.(s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys IVocabularys sIVocabularyTokenizedcBstZdZdZRS(sVocabulary that provides support for tokenized representation. This interface must be used as a mix-in with IBaseVocabulary. Terms returned from getTerm() and provided by iteration must conform to ITitledTokenizedTerm. cCsdS(s1Return an ITokenizedTerm for the passed-in token.N((stoken((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysgetTermByTokens(s__name__s __module__s__doc__sgetTermByToken(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIVocabularyTokenizeds sIVocabularyRegistrycBstZdZdZRS(sHRegistry that provides IBaseVocabulary objects for specific fields. cCsdS(sReturn the vocabulary named 'name' for the content object 'object'. When the vocabulary cannot be found, LookupError is raised. N((sobjectsname((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysgets(s__name__s __module__s__doc__sget(((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pysIVocabularyRegistrys N(Os__doc__szope.interfaces Interfaces Attributeszope.schema._bootstrapfieldssFieldsTextsTextLinesBoolsInts ContainersIterableszope.i18nmessageidsMessageIDFactorys_s zope.schema._bootstrapinterfacessStopValidationsValidationErrors IFromUnicodesRequiredMissings WrongTypesConstraintNotSatisfieds NotAContainers NotAnIteratorsTooSmallsTooBigsTooShortsTooLongs InvalidValuesWrongContainedTypes NotUniquesSchemaNotFullyImplementedsSchemaNotProvideds InvalidURIs InvalidIdsInvalidDottedNames ExceptionsUnboundsIFields IIterables IContainers IOrderablesILensIMinMaxs IMinMaxLensIInterfaceFieldsIBoolsIBytessIASCIIs IBytesLinesITexts ISourceTexts ITextLines IPasswordsIIntsIFloats IDatetimesIDates _is_fields_fieldssIURIsIIdsIChoices ICollections ISequencesIUnorderedCollectionsITuplesIListsISetsIObjectsIDictsITermsITokenizedTermsITitledTokenizedTermsIBaseVocabularysIIterableVocabularys IVocabularysIVocabularyTokenizedsIVocabularyRegistry(IsSchemaNotFullyImplementeds IIterablesTooLongs ContainersIInterfaceFieldsIIterableVocabularysStopValidationsILens WrongTypes NotAContainersFields IFromUnicodesIFloatsBoolsITerms InvalidValuesTooBigsIChoicesIBytessITokenizedTermsIURIsIBools ISourceTexts ITextLinesValidationErrors IBytesLines IPasswordsIMinMaxsConstraintNotSatisfieds InvalidURIsISets NotAnIterators NotUniquesIFields IMinMaxLens Interfaces IVocabularysIUnorderedCollectionsIDatesRequiredMissings ISequences IContainersIDictsInvalidDottedNamesTextLinesIASCIIsIIntsIObjectsIListsSchemaNotProvideds_fieldss InvalidIdsWrongContainedTypesIBaseVocabularys_s _is_fieldsIIdsITitledTokenizedTerms IDatetimesTooShorts IOrderablesITextsInts AttributesIVocabularyTokenizedsITuplesTooSmallsMessageIDFactorysTextsUnbounds ICollectionsIterablesIVocabularyRegistry((s4build/bdist.linux-i686/egg/zope/schema/interfaces.pys?s|%     z     PK4Zzope/schema/accessors.pyc; ]53Dc@s_dZdklZlZdklZdefdYZdefdYZdZdS( sField accessors =============== Accessors are used to model methods used to access data defined by fields. Accessors are fields that work by decorating existing fields. To define accessors in an interface, use the accessors function:: class IMyInterface(Interface): getFoo, setFoo = accessors(Text(title=u'Foo', ...)) getBar, = accessors(TextLine(title=u'Foo', readonly=True, ...) Normally a read accessor and a write accessor are defined. Only a read accessor is defined for read-only fields. Read accessors function as access method specifications and as field specifications. Write accessors are solely method specifications. $Id: accessors.py 25177 2004-06-02 13:17:31Z jim $ (s providedBys implementedBy(sMethodsFieldReadAccessorcBsntZdZdZeeZdZdZdZdZe dZ dZ dZ d Z RS( sField read accessor cCst|ittSdS(N(s providedBysselfsfields implementedBysFieldReadAccessor(sself((s3build/bdist.linux-i686/egg/zope/schema/accessors.pys __provides__2scCs-||_ti|dd|i|_dS(Nssget %s(sfieldsselfsMethods__init__s__doc__(sselfsfield((s3build/bdist.linux-i686/egg/zope/schema/accessors.pys__init__6s cCsdSdS(Ns()((sself((s3build/bdist.linux-i686/egg/zope/schema/accessors.pysgetSignatureString;scCs5hdf<df<df<dt<dtscCst||iSdS(N(sgetattrsobjectsselfs__name__(sselfsobject((s3build/bdist.linux-i686/egg/zope/schema/accessors.pysgetFscCst||iSdS(N(sgetattrsobjectsselfs__name__(sselfsobjectsdefault((s3build/bdist.linux-i686/egg/zope/schema/accessors.pysqueryIscCs7|iotdnt||ii|dS(Ns$Can't set values on read-only fields(sselfsreadonlys TypeErrorsgetattrsobjectswriters__name__svalue(sselfsobjectsvalue((s3build/bdist.linux-i686/egg/zope/schema/accessors.pyssetLs cCst|i|SdS(N(sgetattrsselfsfieldsname(sselfsname((s3build/bdist.linux-i686/egg/zope/schema/accessors.pys __getattr__QscCsE|ii|i}|ii|i|ii||_|SdS(N( sselfs __class__s__new__sclones__dict__supdatesfieldsbindsobject(sselfsobjectsclone((s3build/bdist.linux-i686/egg/zope/schema/accessors.pysbindTs(s__name__s __module__s__doc__s __provides__spropertys__init__sgetSignatureStringsgetSignatureInfosgetsNonesqueryssets __getattr__sbind(((s3build/bdist.linux-i686/egg/zope/schema/accessors.pysFieldReadAccessor*s          sFieldWriteAccessorcBs#tZdZdZdZRS(NcCs-ti|d||_d|i|_dS(Nssset %s(sMethods__init__sselfsfields__doc__(sselfsfield((s3build/bdist.linux-i686/egg/zope/schema/accessors.pys__init__\s cCsdSdS(Ns (newvalue)((sself((s3build/bdist.linux-i686/egg/zope/schema/accessors.pysgetSignatureStringascCs;hddf<ddf<df<dt<dtInitialize the vocabulary given a list of terms. The vocabulary keeps a reference to the list of terms passed in; it should never be modified while the vocabulary is used. One or more interfaces may also be provided so that alternate widgets may be bound without subclassing. s<Supplied vocabulary values resulted in duplicate term tokensN( sselfsby_valuesby_tokenstermss_termsstermsvaluestokenslens ValueErrors interfacessdirectlyProvides(sselfstermss interfacessterm((s4build/bdist.linux-i686/egg/zope/schema/vocabulary.pys__init__3s    7cGsJgi}|D]"\}}||i||q~}|||SdS(sConstruct a vocabulary from a list of (token, value) pairs. The order of the items is preserved as the order of the terms in the vocabulary. Terms are created by calling the class method createTerm() with the pair (value, token). One or more interfaces may also be provided so that alternate widgets may be bound without subclassing. N( sappends_[1]sitemsstokensvaluesclss createTermstermss interfaces(sclssitemss interfacesstermssvalues_[1]stoken((s4build/bdist.linux-i686/egg/zope/schema/vocabulary.pys fromItemsHs 9cGsAgi}|D]}||i|q~}|||SdS(sConstruct a vocabulary from a simple list. Values of the list become both the tokens and values of the terms in the vocabulary. The order of the values is preserved as the order of the terms in the vocabulary. Tokens are created by calling the class method createTerm() with the value as the only parameter. One or more interfaces may also be provided so that alternate widgets may be bound without subclassing. N(sappends_[1]svaluessvaluesclss createTermstermss interfaces(sclssvaluess interfacesstermssvalues_[1]((s4build/bdist.linux-i686/egg/zope/schema/vocabulary.pys fromValuesVs 0cGst|SdS(sCreate a single term from data. Subclasses may override this with a class method that creates a term of the appropriate type from the arguments. N(s SimpleTermsargs(sclssargs((s4build/bdist.linux-i686/egg/zope/schema/vocabulary.pys createTermfscCs/y||ijSWntj o tSnXdS(s*See zope.schema.interfaces.IBaseVocabularyN(svaluesselfsby_values TypeErrorsFalse(sselfsvalue((s4build/bdist.linux-i686/egg/zope/schema/vocabulary.pys __contains__os cCs5y|i|SWntj ot|nXdS(s*See zope.schema.interfaces.IBaseVocabularyN(sselfsby_valuesvaluesKeyErrors LookupError(sselfsvalue((s4build/bdist.linux-i686/egg/zope/schema/vocabulary.pysgetTermws cCs5y|i|SWntj ot|nXdS(s/See zope.schema.interfaces.IVocabularyTokenizedN(sselfsby_tokenstokensKeyErrors LookupError(sselfstoken((s4build/bdist.linux-i686/egg/zope/schema/vocabulary.pysgetTermByToken~s cCst|iSdS(s.See zope.schema.interfaces.IIterableVocabularyN(sitersselfs_terms(sself((s4build/bdist.linux-i686/egg/zope/schema/vocabulary.pys__iter__scCst|iSdS(s.See zope.schema.interfaces.IIterableVocabularyN(slensselfsby_value(sself((s4build/bdist.linux-i686/egg/zope/schema/vocabulary.pys__len__s(s__name__s __module__s__doc__s implementss IVocabularysIVocabularyTokenizeds__init__s fromItemss classmethods fromValuess createTerms __contains__sgetTermsgetTermByTokens__iter__s__len__(((s4build/bdist.linux-i686/egg/zope/schema/vocabulary.pysSimpleVocabulary.s            sVocabularyRegistryErrorcBstZdZdZRS(NcCs#||_ti|t|dS(N(snamesselfs Exceptions__init__sstr(sselfsname((s4build/bdist.linux-i686/egg/zope/schema/vocabulary.pys__init__s cCsd|iSdS(Nsunknown vocabulary: %r(sselfsname(sself((s4build/bdist.linux-i686/egg/zope/schema/vocabulary.pys__str__s(s__name__s __module__s__init__s__str__(((s4build/bdist.linux-i686/egg/zope/schema/vocabulary.pysVocabularyRegistryErrors sVocabularyRegistrycBs6tZdfZeedZdZdZRS(Ns_mapcCs h|_dS(N(sselfs_map(sself((s4build/bdist.linux-i686/egg/zope/schema/vocabulary.pys__init__scCsAy|i|}Wntj ot|nX||SdS(s.See zope.schema.interfaces.IVocabularyRegistryN(sselfs_mapsnamesvtypesKeyErrorsVocabularyRegistryErrorsobject(sselfsobjectsnamesvtype((s4build/bdist.linux-i686/egg/zope/schema/vocabulary.pysgets cCs||i|