[Zope3-checkins] CVS: Zope3/lib/python/Zope/Schema - Converter.py:1.1 ErrorNames.py:1.1 Exceptions.py:1.1 IConverter.py:1.1 IField.py:1.1 IValidator.py:1.1 Validator.py:1.1 _Field.py:1.1 _Schema.py:1.1 __init__.py:1.1

Jim Fulton jim@zope.com
Thu, 5 Sep 2002 14:55:05 -0400


Update of /cvs-repository/Zope3/lib/python/Zope/Schema
In directory cvs.zope.org:/tmp/cvs-serv21741/lib/python/Zope/Schema

Added Files:
	Converter.py ErrorNames.py Exceptions.py IConverter.py 
	IField.py IValidator.py Validator.py _Field.py _Schema.py 
	__init__.py 
Log Message:
Moved the Schema package into the Zope package.

Also cleaned up a bunch of "from x import *".


=== Added File Zope3/lib/python/Zope/Schema/Converter.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.0 (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.
# 
##############################################################################
"""
$Id: Converter.py,v 1.1 2002/09/05 18:55:03 jim Exp $
"""
from IConverter import IConverter
from Exceptions import ConversionError

# XXX is it worth is doing isImplementedBy checks in converters (input values)?
# if evil code could corrupt matters yes, but can it? (after all
# it'll also have to pass validation, unless the converter framework
# is used independently..something to ponder)

class NullConverter(object):
    """A converter that really doesn't do a thing.
    """
    __implements__ = IConverter

    def convert(self, value):
        return value

class CombinedConverter(object):
    """A converter that chains several converters to each other.
    """
    __implements__ = IConverter

    def __init__(self, converters):
        self._converters = converters
    
    def convert(self, value):
        for converter in self._converters:
            value = converter.convert(value)
        return value

class FunctionConverter(object):
    """Use a Python function to convert.
    Turns *any* Python exception into a conversion error.
    XXX Is this good/useful?
    """
    __implements__ = IConverter    

    def convert(self, value):
        try:
            return self._function(value)
        except Exception, e:
            raise ConversionError('Conversion error', e)
        
def _functionConverterFactory(klass_name, function):
    """Create a derived class of FunctionConvert which uses function.
    """
    klass = type(klass_name, (FunctionConverter,), {})
    klass._function = function
    return klass

StrToIntConverter= _functionConverterFactory('StrToIntConverter', int)
IntToStrConverter = _functionConverterFactory('IntToStrConverter', str)

StrToFloatConverter = _functionConverterFactory('StrToFloatConverter', float)
FloatToStrConverter = _functionConverterFactory('FloatToStrConverter', str)


class FileToStrConverter(object):
    __implements__ = IConverter    

    def convert(self, value):
        try:
            value = value.read()
        except Exception, e:
            raise ConversionError('Value is not a file object', e)
        else:
            if len(value):
                return value
            else:
                return None


=== Added File Zope3/lib/python/Zope/Schema/ErrorNames.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.0 (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.
# 
##############################################################################
"""Common Schema Error Names

$Id: ErrorNames.py,v 1.1 2002/09/05 18:55:03 jim Exp $
"""
WrongType = "WrongType"

RequiredMissing ='RequiredMissing'

RequiredEmptyStr = 'RequiredEmptyString'

TooBig = 'TooBig'

TooSmall = 'TooSmall'

TooLong = 'TooLong'

TooShort = 'TooShort'

InvalidValue = 'InvalidValue'

TooManyDecimals = 'TooManyDecimals'

WrongContainedType = "WrongContainedType"

NotEnoughElements = 'NotEnoughElements'

TooManyElements = 'TooManyElements'


=== Added File Zope3/lib/python/Zope/Schema/Exceptions.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.0 (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.
# 
##############################################################################
"""Validation Exceptions

$Id: Exceptions.py,v 1.1 2002/09/05 18:55:03 jim Exp $
"""

class StopValidation(Exception):
    """This exception is raised, if the validation is done for sure early.
    Note that this exception should be always caught, since it is just a
    way for the validator to save time."""
    pass


class ValidationError(Exception):
    """If some check during the Validation process fails, this exception is
    raised."""

    def __init__(self, error_name):
        Exception.__init__(self)
        self.error_name = error_name

    def __cmp__(self, other):
        return cmp(self.error_name, other.error_name)


class ConversionError(Exception):
    """If some conversion fails, this exception is raised."""

    def __init__(self, error_name, original_exception=None):
        Exception.__init__(self)
        self.error_name = error_name
        self.original_exception = original_exception


class ErrorContainer(Exception):
    """ """

    def __init__(self, errors):
        Exception.__init__(self)
        self.errors = errors

    def __len__(self):
        return len(self.errors)

    def __getitem__(self, key):
        return self.errors[key]

    def __iter__(self):
        return iter(self.errors)


class ValidationErrorsAll(ErrorContainer):
    """This is a collection error that contains all exceptions that occured
    during the validation process."""


class ConversionErrorsAll(ErrorContainer):
    """This is a collection error that contains all exceptions that occured
    during the conversion process."""



=== Added File Zope3/lib/python/Zope/Schema/IConverter.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.0 (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.
# 
##############################################################################
"""
$Id: IConverter.py,v 1.1 2002/09/05 18:55:03 jim Exp $
"""
from Interface import Interface

class IConverter(Interface):
    """A converter can convert a value from one type to another."""

    def convert(value):
        """Call an IConverter with a value, and it will try to convert to
        another value and return the result. If conversion cannot take
        place, the convertor will raise a ConversionError. (or a
        ValidationError in case of Converters using Schemas inside?)
        """
    


=== Added File Zope3/lib/python/Zope/Schema/IField.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.0 (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.
# 
##############################################################################
"""These are the interfaces for the common fields.

$Id: IField.py,v 1.1 2002/09/05 18:55:03 jim Exp $
"""
from Interface import Interface
import _Field as Field

class IField(Interface):
    """All fields conform to this schema. Note that the interpretation
    of 'required' is up to each field by itself. For some fields, such as
    IBool, requiredness settings may make no difference.
    """

    title = Field.Str(
        title="Title",
        description="Title.",
        default=""
        )
    
    description = Field.Str(
        title="Description",
        description="Description.",
        default="",
        required=0)

    readonly = Field.Bool(
        title="Read Only",
        description="Read-only.",
        default=0)
    
    required = Field.Bool(
        title="Required",
        description="Required.",
        default=1)


class ISingleValueField(IField):
    """This field consists always only of one value and it not a homogeneous
    container, like a list. Note that structures and instances of classes
    might or might not be ISingleValueFields."""
    
    allowed_values = Field.Tuple(
        title="Allowed Values",
        description="Only values specified here can be values of this field. "
                    "If the list is empty, then there are no further "
                    "restictions.",
        required=0,
        default=())
        

    
class IBool(ISingleValueField):
    """Describes the footprint of a Bool variable."""

    default = Field.Bool(
        title="Default",
        description="Default.",
        default=0)


class IStr(ISingleValueField):
    """Describes the footprint of a Str variable."""

    default = Field.Str(
        title="Default",
        description="Default.",
        default="")
    
    min_length = Field.Int(
        title="Minimum length",
        description=("Value after whitespace processing cannot have less than "
                     "min_length characters. If min_length is None, there is "
                     "no minimum."),
        required=0,
        min=0, # needs to be a positive number
        default=0)

    max_length = Field.Int(
        title="Maximum length",
        description=("Value after whitespace processing cannot have greater "
                     "or equal than max_length characters. If max_length is "
                     "None, there is no maximum."),
        required=0,
        min=0, # needs to be a positive number
        default=None)

    
class IInt(ISingleValueField):
    """Describes the footprint of an Int variable."""

    default = Field.Int(
        title="Default",
        description="Default.",
        default=0)
    
    min = Field.Int(
        title="Minimum",
        description="The minimal numerical value accepted. If min is None, "
                    "there is no minimum.",
        required=0,
        default=0)

    max = Field.Int(
        title="Maximum",
        description="The masximal numerical value accepted. If min is None, "
                    "there is no minimum.",
        required=0,
        default=None)
    
    
class IFloat(ISingleValueField):
    """Describes the footprint of a Float variable."""

    default = Field.Float(
        title="Default",
        description="Default.",
        default=0)
    
    min = Field.Float(
        title="Minimum",
        description="The minimal numerical value accepted. If min is None, "
                    "there is no minimum.",
        required=0,
        default=0)

    max = Field.Float(
        title="Maximum",
        description="The masximal numerical value accepted. If min is None, "
                    "there is no minimum.",
        required=0,
        default=None)
    
    decimals = Field.Int(
        title="Decimal Places",
        description="Defines the amount of decimal places the floating point "
                    "can have. This value is also know as precision. If the "
                    "value is None, no precision is required.",
        required=0,
        default=None)


class IMultipleValueField(IField):
    """This field will contain some sort of collection of objects whose types
    can be often defined through a finite set of types."""

    value_types = Field.Tuple(
        title="Value Types",
        description="Defines the value types that are allowed in the list. "
                    "If the list is empty, then all types are allowed.",
        required=0,
        default=())

    min_values = Field.Int(
        title="Minimum amount of values",
        description="The minimum amount of values in the list. If min_values "
                    "is None, there is no minimum.",
        min=0,
        required=0,
        default=0)

    max_values = Field.Int(
        title="Maximum amount of values",
        description="The maximum amount of values in the list. If max_values "
                    "is None, there is no maximum.",
        min=0,
        required=0,
        default=None)


class ITuple(IMultipleValueField):
    """Describes the footprint of a Tuple variable."""

    default = Field.Tuple(
        title="Default",
        description="Default.",
        default=())    


class IList(ITuple):
    """Describes the footprint of a List variable."""

    default = Field.List(
        title="Default",
        description="Default.",
        default=[])


class IDict(IMultipleValueField):
    """Describes the footprint of a Dict variable."""

    default = Field.Dict(
        title="Default",
        description="Default.",
        default={})    

    key_types = Field.Tuple(
        title="Value Types",
        description="Defines the key types that are allowed in the "
                    "dictionary. If the list is empty, then all types "
                    "are allowed.",
        required=0,
        default=())


=== Added File Zope3/lib/python/Zope/Schema/IValidator.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.0 (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.
# 
##############################################################################
"""
$Id: IValidator.py,v 1.1 2002/09/05 18:55:03 jim Exp $
"""
from Interface import Interface

class IValidator(Interface):
    """Validates a particular value against the specifed field. Each
    Validator just does one check, like check for the max value or the
    min value!

    Note that the responsibility of Validator is not to change the
    value, only to raise an exception in case the value was incorrect.
    Converters are used to change values.
    
    It should be always implemented as an adapter.
    """

    def validate(value):
        """Validate the the value.

        This should not return anything, only raise an exception in case
        of an invalid value.""" 


=== Added File Zope3/lib/python/Zope/Schema/Validator.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.0 (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.
# 
##############################################################################
"""
$Id: Validator.py,v 1.1 2002/09/05 18:55:03 jim Exp $
"""
from types import ListType, TupleType
ListTypes = (ListType, TupleType)
from Zope.Schema.IValidator import IValidator
#from Zope.Schema.IField import *
from Zope.Schema._Field import List

from Zope.Schema.Exceptions import StopValidation, ValidationError
import ErrorNames

class Validator:
    """Validator base class"""
    __implements__ =  IValidator

    def __init__(self, field):
        self.field = field
    
    def getDescription(self):
        return self.__doc__

    def validate(self, value):
        'See Zope.Schema.IValidator.IValidator'
        pass


class TypeValidator(Validator):
    """Check whether the value is of the correct type."""
    def validate(self, value):
        'See Zope.Schema.IValidator.IValidator'
        t = self.field.type
        if t is not None and value is not None and not isinstance(value, t):
            raise ValidationError, ErrorNames.WrongType

class RequiredValidator(Validator):
    """If no value was passed, check whether the field was required."""
    def validate(self, value):
        'See Zope.Schema.IValidator.IValidator'
        if value is None:
            if self.field.required:
                raise ValidationError, ErrorNames.RequiredMissing
            else:
                # we are done with validation for sure
                raise StopValidation

class StrRequiredValidator(Validator):
    """Don't accept empty strings for a required field."""
    def validate(self, value):
        'See Zope.Schema.IValidator.IValidator'
        if self.field.required and value == '':
            raise ValidationError, ErrorNames.RequiredEmptyStr

class MinimumLengthValidator(Validator):
    """Check that the length is larger than the minimum."""
    def validate(self, value):
        'See Zope.Schema.IValidator.IValidator'
        length = len(value)
        if self.field.min_length is not None and \
               length < self.field.min_length:
            raise ValidationError, ErrorNames.TooShort

class MaximumLengthValidator(Validator):
    """Check that the length is smaller than the maximum."""
    def validate(self, value):
        'See Zope.Schema.IValidator.IValidator'
        length = len(value)
        if self.field.max_length is not None and \
               length > self.field.max_length:
            raise ValidationError, ErrorNames.TooLong

class MinimumValueValidator(Validator):
    """Check that the value is larger than the minimum."""
    def validate(self, value):
        'See Zope.Schema.IValidator.IValidator'
        if self.field.min is not None and value < self.field.min:
            raise ValidationError, ErrorNames.TooSmall

class MaximumValueValidator(Validator):
    """Check that the value is smaller than the maximum."""
    def validate(self, value):
        'See Zope.Schema.IValidator.IValidator'
        if self.field.max is not None and value > self.field.max:
            raise ValidationError, ErrorNames.TooBig

class AllowedValuesValidator(Validator):
    """Check whether the value is one of the allowed values."""
    def validate(self, value):
        'See Zope.Schema.IValidator.IValidator'
        allowed = self.field.allowed_values
        if len(allowed) > 0 and value not in allowed:
            raise ValidationError, ErrorNames.InvalidValue

class DecimalsValidator(Validator):
    """Check that the float value has the right precision."""
    def validate(self, value):
        'See Zope.Schema.IValidator.IValidator'
        value_str = str(value)
        try:
            decimals = len(value_str.split('.')[1])
        except IndexError:
            decimals = 0
        if self.field.decimals and  decimals > self.field.decimals:
            raise ValidationError, ErrorNames.TooManyDecimals

def _flatten(list):
    out = []
    for elem in list:
        if isinstance(elem, ListTypes):
            out += _flatten(elem)
        else:
            out.append(elem)
    return out

class ListValueTypeValidator(Validator):
    """Check that all list elements have the right type."""
    def validate(self, value):
        'See Zope.Schema.IValidator.IValidator'
        if self.field.value_types:
            types = map(lambda field: field.type, self.field.value_types)
            types = tuple(_flatten(types))
            for val in value:
                if not isinstance(val, types):
                    raise ValidationError, ErrorNames.WrongContainedType

class MinimumAmountOfItemsValidator(Validator):
    """Check whether the list contains enough items."""
    def validate(self, value):
        'See Zope.Schema.IValidator.IValidator'
        if self.field.min_values and value is not None and \
               len(value) < self.field.min_values:
            raise ValidationError, ErrorNames.NotEnoughElements

class MaximumAmountOfItemsValidator(Validator):
    """Check whether the list contains not too many items."""
    def validate(self, value):
        'See Zope.Schema.IValidator.IValidator'
        if self.field.max_values and len(value) > self.field.max_values:
            raise ValidationError, ErrorNames.TooManyElements

class DictKeyTypeValidator(Validator):
    """Check that the values in the value have the right type."""
    def validate(self, value):
        'See Zope.Schema.IValidator.IValidator'
        keys = value.keys()
        field = List(id='temp', title='temp',
                     value_types=self.field.key_types)
        validator = ListValueTypeValidator(field)
        validator.validate(keys)

class DictValueTypeValidator(Validator):
    """Check that the values in the value have the right type."""
    def validate(self, value):
        'See Zope.Schema.IValidator.IValidator'
        values = value.values()
        field = List(id='temp', title='temp',
                     value_types=self.field.value_types)
        validator = ListValueTypeValidator(field)
        validator.validate(values)

class CombinedValidator(Validator):
    """Combine several validators into a larger one."""
    validators = []

    def validate(self, value):
        'See Zope.Schema.IValidator.IValidator'        
        for validator in self.validators:
            try:
                validator(self.field).validate(value)
            except StopValidation:
                return

class BaseValidator(CombinedValidator):
    """A simple base validator."""
    validators = [TypeValidator, RequiredValidator, AllowedValuesValidator] 

class SimpleValidator(BaseValidator):
    """Validator for values of simple type.
    A simple type cannot be further decomposed into other types.""" 

class StrValidator(SimpleValidator):
    """Completely validates a Str Field."""
    validators = SimpleValidator.validators + [StrRequiredValidator,
                                               MinimumLengthValidator,
                                               MaximumLengthValidator]

class BoolValidator(SimpleValidator):
    """Completely validates a Bool Field."""

class IntValidator(SimpleValidator):
    """Completely validates a Int Field."""
    validators = SimpleValidator.validators + [MinimumValueValidator,
                                               MaximumValueValidator]

class FloatValidator(SimpleValidator):
    """Completely validates a Float Field."""
    validators = SimpleValidator.validators + [MinimumValueValidator,
                                               MaximumValueValidator,
                                               DecimalsValidator]

class CompositeValidator(BaseValidator):
    """Validator for values of composite type.
    A a composite type one composed of several others, i.e. an
    object but also a list, tuple or mapping."""

class MultiValueValidator(BaseValidator):
    """Validator for Single Value Fields"""
    validators = BaseValidator.validators + [
        ListValueTypeValidator,
        MinimumAmountOfItemsValidator, MaximumAmountOfItemsValidator] 

class TupleValidator(MultiValueValidator):
    """Completely validates a Tuple Field."""

class ListValidator(TupleValidator):
    """Completely validates a List Field."""

class DictValidator(CompositeValidator):
    """Completely validates a Dict Field."""
    validators = CompositeValidator.validators + [
        DictKeyTypeValidator, DictValueTypeValidator,
        MinimumAmountOfItemsValidator, MaximumAmountOfItemsValidator] 



=== Added File Zope3/lib/python/Zope/Schema/_Field.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.0 (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.
# 
##############################################################################
"""
$Id: _Field.py,v 1.1 2002/09/05 18:55:03 jim Exp $
"""
from Interface.Attribute import Attribute
from Interface.Implements import objectImplements

from Exceptions import StopValidation, ValidationError
import ErrorNames


class Field(Attribute):
    # we don't implement the same interface Attribute
    __implements__ = ()
    type = None
    default = None
    setter = None
    getter = None
    required = 0
    allowed_values = []
    
    def __init__(self, **kw):
        """Pass in field values as keyword parameters."""
        for key, value in kw.items():
            setattr(self, key, value)
        # __name__ to '', so interface should initialize this with
        # name of attribute
        super(Field, self).__init__('')

    def validate(self, value):
        try:
            return self.validator(self).validate(value)
        except StopValidation:
            return value

class Str(Field):
    """A field representing a Str."""
    type = str, unicode
    min_length = None
    max_length = None

class Bool(Field):
    """A field representing a Bool."""
    # XXX Do we really expect this to be an int?
    # The BoolTest only work if Bool corresponds to Python's int.
    type = int

class Int(Field):
    """A field representing a Integer."""
    type = int
    min = max = None

class Float(Field):
    """A field representing a Floating Point."""
    type = float, int
    min = max = None
    decimals = None

class Tuple(Field):
    """A field representing a Tuple."""
    type = tuple
    value_types = None
    min_values = max_values = None

class List(Field):
    """A field representing a List."""
    type = list
    value_types = None
    min_values = max_values = None

class Dict(Field):
    """A field representing a Dict."""
    type = dict
    min_values = max_values = None
    key_types = value_types = None


=== Added File Zope3/lib/python/Zope/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.0 (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.
# 
##############################################################################
"""
$Id: _Schema.py,v 1.1 2002/09/05 18:55:03 jim Exp $
"""
from Interface import Interface
import Validator
from Zope.Schema.Exceptions import \
     StopValidation, ValidationError, ValidationErrorsAll
    
def getFields(schema):
    """Get all fields on a schema.
    """
    from IField import IField
    fields = {}
    for name in schema.names(1):
        attr = schema.getDescriptionFor(name)
        if IField.isImplementedBy(attr):
            fields[name] = attr
    return fields


# validate functions either return silently, or raise a ValidationError
# or in case of the validate*All functions, a ValidationErrosAll exception.
# this should somehow be stated in an interface.

def validateMapping(schema, values):
    """Pass in field values in mapping and validate whether they
    conform to schema. Stop at first error.
    """
    from IField import IField
    for name in schema.names(1):
        attr = schema.getDescriptionFor(name)
        if IField.isImplementedBy(attr):
            attr.validate(values.get(name))

def validateMappingAll(schema, values):
    """Pass in field values in mapping and validate whether they
    conform to schema.
    """
    errors = []
    from IField import IField
    for name in schema.names(1):
        attr = schema.getDescriptionFor(name)
        if IField.isImplementedBy(attr):
            try:
                attr.validate(values.get(name))
            except ValidationError, e:
                errors.append((name, e))
    if errors:
        raise ValidationErrorsAll, errors

# Now we can create the interesting interfaces and wire them up:
def wire():
    from Interface.Implements import implements

    from IField import IField
    from _Field import Field
    implements(Field, IField, 0)
    Field.validator = Validator.RequiredValidator

    from IField import IBool
    from _Field import Bool
    implements(Bool, IBool, 0)
    Bool.validator = Validator.BoolValidator

    from IField import IStr
    from _Field import Str
    implements(Str, IStr, 0)
    Str.validator = Validator.StrValidator

    from IField import IInt
    from _Field import Int
    implements(Int, IInt, 0)
    Int.validator = Validator.IntValidator

    from IField import IFloat
    from _Field import Float
    implements(Float, IFloat, 0)
    Float.validator = Validator.FloatValidator

    from IField import ITuple
    from _Field import Tuple
    implements(Tuple, ITuple, 0)
    Tuple.validator = Validator.TupleValidator

    from IField import IList
    from _Field import List
    implements(List, IList, 0)
    List.validator = Validator.ListValidator

    from IField import IDict
    from _Field import Dict
    implements(Dict, IDict, 0)
    Dict.validator = Validator.DictValidator


wire()
del wire



=== Added File Zope3/lib/python/Zope/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.0 (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,v 1.1 2002/09/05 18:55:03 jim Exp $
"""
from _Field import Field, Str, Bool, Int, Float, Tuple, List, Dict
from _Schema import validateMapping, validateMappingAll, getFields