[Zope-Checkins] CVS: Zope3/lib/python/Schema - Exceptions.py:1.1 IField.py:1.1 _Field.py:1.1 _Schema.py:1.1 __init__.py:1.1

Martijn Faassen m.faassen@vet.uu.nl
Mon, 24 Jun 2002 04:31:49 -0400


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

Added Files:
	Exceptions.py IField.py _Field.py _Schema.py __init__.py 
Log Message:
Added beginnings of schema.


=== Added File Zope3/lib/python/Schema/Exceptions.py ===

class StopValidation(Exception):
    pass

class ValidationError(Exception):
    pass


=== Added File Zope3/lib/python/Schema/IField.py ===
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
    IBoolean, 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 IBool(IField):
    default = Field.Bool(
        title="Default",
        description="Default.",
        default=0)

class IStr(IField):

    default = Field.Str(
        title="Default",
        description="Default.",
        default="")
    
    # whitespace = Field.Selection(
    #     title="Whitespace",
    #     description="preserve: whitespace is preserved."
    #                 "replace: all occurences of tab, line feed and "
    #                 "carriage return are replaced with space characters. "
     #                 "collapse: first process as in 'replace', then "
    #                 "collapse all spaces to a single space, and strip any "
    #                 "spaces from front and back."
    #                 "strip: strip off whitespace from front and back.",
    #     items=[("preserve", "preserve"),
    #            ("replace", "replace"),
    #            ("collapse", "collapse"),
    #            ("strip", "strip")],
    #     selection_type=IStr,
    #     default="strip")

    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)

##     pattern = Str(
##         title="Pattern",
##         description="A regular expression by which the value "
##                     "(after whitespace processing) should be constrained."
##                     "If None, no pattern checking is performed.",
        
##         default=None,
##         required=0)
    
class IInt(IField):
    default = Field.Int(
        title="Default",
        description="Default.",
        default=0)
    
    min = Field.Int(
        title="Minimum",
        description="Value after whitespace processing cannot have less than "
                    "min characters. If min is None, there is no minimum.",
        required=0,
        min=0,
        default=0)

    max = Field.Int(
        title="Maximum",
        description="Value after whitespace processing cannot have greater or "
                    "equal than max characters. If max is None, there is no "
                    "maximum.",
        required=0,
        min=0,
        default=None)

##    pattern = Field.Str(
##         title="Pattern",
##         description="A regular expression by which the value "
##                     "(after whitespace processing) should be constrained."
##                     "If None, no pattern checking is performed.",
        
##         default=None,
##         required=0)
    
    


=== Added File Zope3/lib/python/Schema/_Field.py ===
from Interface.Attribute import Attribute
from Interface.Implements import objectImplements

from Exceptions import StopValidation, ValidationError
#from _Schema import validate

class Field(Attribute):

    # we don't implement the same interface Attribute
    __implements__ = ()

    default = None
    required = 0
    
    def __init__(self, **kw):
        """
        Pass in field values as keyword parameters.
        """
        for key, value in kw.items():
            setattr(self, key, value)
        super(Field, self).__init__(self.title or 'no title')
    
    def validate(self, value):
        try:
            return self._validate(value)
        except StopValidation:
            return None

    def _validate(self, value):
        if value is None:
            if self.required:
                raise ValidationError, "Must be required"
            else:
                # we are done with validation for sure
                raise StopValidation
        return value
    
class Str(Field):
    
    min_length = None
    max_length = None

    def _validate(self, value):
        value = super(Str, self)._validate(value)
        if self.required and value == '':
            raise ValidationError, "Required string is empty."
        length = len(value)
        if self.min_length is not None and length < self.min_length:
            raise ValidationError, "Too short."
        if self.max_length is not None and length >= self.max_length:
            raise ValidationError, "Too long."
        return value
    
class Bool(Field):
        
    def _validate(self, value):
        value = super(Bool, self)._validate(value)
        return not not value
    
class Int(Field):

    min = max = None

    def _validate(self, value):
        value = super(Int, self)._validate(value)
        if self.min is not None and value < self.min:
            raise ValidationError, "Too small"
        if self.max is not None and value >= self.max:
            raise ValidationError, "Too big"
        return value
    
class DateTime(Field):
    pass



=== Added File Zope3/lib/python/Schema/_Schema.py ===

def validate(schema, values):
    """Pass in field values in dictionary and validate whether they
    conform to schema. Return validated values.
    """
    from IField import IField
    result = {}
    for name in schema.names(1):
        attr = schema.getDescriptionFor(name)
        if IField.isImplementedBy(attr):
            result[name] = attr.validate(values.get(name))
    return result
    
# 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)
    
    from IField import IBool
    from _Field import Bool
    implements(Bool, IBool, 0)

    from IField import IStr
    from _Field import Str
    implements(Str, IStr, 0)

    from IField import IInt
    from _Field import Int
    implements(Int, IInt, 0)

    
wire()
del wire 



=== Added File Zope3/lib/python/Schema/__init__.py ===
from _Field import Field, Int, Bool, Str