def to_python(self, value, state=None):
     try:
         if not value:
             return datetime.utcnow()
         return datetime.strptime(value, '%Y-%m-%d')
     except:
         raise TGValidationError(_('Expected date in format 2013-01-11'))
Beispiel #2
0
            def _to_python(self, value):
                if not value:
                    return value

                if value == 'True':
                    return True
                raise TGValidationError('Not True')
Beispiel #3
0
            def to_python(self, value, state=None):
                try:
                    pyv = self._to_python(value)
                except Exception as e:
                    raise TGValidationError(str(e))

                self.validate_python(pyv, None)
                return pyv
Beispiel #4
0
    def _perform_validate(self, controller, params):
        """Run validation for the controller with the given parameters.

        Validation is stored on the "validation" attribute of the controller's
        decoration.

        If can be in three forms:

        1) A dictionary, with key being the request parameter name, and value a
           FormEncode validator.

        2) A FormEncode Schema object

        3) Any object with a "validate" method that takes a dictionary of the
           request variables.

        Validation can "clean" or otherwise modify the parameters that were
        passed in, not just raise an exception.  Validation exceptions should
        be FormEncode Invalid objects.

        """

        validation = getattr(controller.decoration, 'validation', None)

        if validation is None:
            return params

        # An object used by FormEncode to get translator function
        formencode_state = type('state', (), {'_': staticmethod(pylons_formencode_gettext)})

        #Initialize new_params -- if it never gets updated just return params
        new_params = {}

        # The validator may be a dictionary, a FormEncode Schema object, or any
        # object with a "validate" method.
        if isinstance(validation.validators, dict):
            # TG developers can pass in a dict of param names and FormEncode
            # validators.  They are applied one by one and builds up a new set
            # of validated params.

            errors = {}
            for field, validator in validation.validators.items():
                try:
                    if isinstance(validator, _FormEncodeValidator):
                        new_params[field] = validator.to_python(params.get(field),
                                                                formencode_state)
                    else:
                        new_params[field] = validator.to_python(params.get(field))
                # catch individual validation errors into the errors dictionary
                except validation_errors as inv:
                    errors[field] = inv

            # Parameters that don't have validators are returned verbatim
            for param, param_value in params.items():
                if not param in new_params:
                    new_params[param] = param_value

            # If there are errors, create a compound validation error based on
            # the errors dictionary, and raise it as an exception
            if errors:
                raise TGValidationError(TGValidationError.make_compound_message(errors),
                                        value=params,
                                        error_dict=errors)

        elif isinstance(validation.validators, _FormEncodeSchema):
            # A FormEncode Schema object - to_python converts the incoming
            # parameters to sanitized Python values
            new_params = validation.validators.to_python(params, formencode_state)

        elif (hasattr(validation.validators, 'validate')
              and getattr(validation, 'needs_controller', False)):
            # An object with a "validate" method - call it with the parameters
            new_params = validation.validators.validate(
                controller, params, formencode_state)

        elif hasattr(validation.validators, 'validate'):
            # An object with a "validate" method - call it with the parameters
            new_params = validation.validators.validate(params, formencode_state)

        # Theoretically this should not happen...
        # if new_params is None:
        #     return params

        return new_params
 def test_validation_error_has_message(self):
     e = TGValidationError('This is a validation error')
     assert str(e) == 'This is a validation error'
Beispiel #6
0
 def to_python(self, value):
     try:
         return int(value)
     except:
         raise TGValidationError('Not a number')
Beispiel #7
0
 def _to_python(self, value):
     if '@' not in value:
         raise TGValidationError('not email')
     return value
Beispiel #8
0
 def _to_python(self, value):
     try:
         return int(value)
     except:
         raise TGValidationError('Must be an integer')
Beispiel #9
0
 def validate_python(self, value, state=None):
     if not value:
         raise TGValidationError('Empty')