How to use the formencode.api.Invalid function in FormEncode

To help you get started, we’ve selected a few FormEncode examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mediadrop / mediadrop / mediadrop / validation / uri_validator.py View on Github external
def raise_error_bad_url(self, value, state):
        msg = _('That is not a valid URL.')
        raise Invalid(msg, value, state)
github beaker-project / beaker / Server / bkr / server / xmlrpccontroller.py View on Github external
response = self.process_rpc(method,params)
            response = xmlrpclib.dumps((response,), methodresponse=1, allow_none=True)
            session.flush()
        except identity.IdentityFailure, e:
            session.rollback()
            response = xmlrpclib.dumps(xmlrpclib.Fault(1,"%s: %s" % (e.__class__, str(e))))
        except xmlrpclib.Fault, fault:
            session.rollback()
            log.exception('Error handling XML-RPC method')
            # Can't marshal the result
            response = xmlrpclib.dumps(fault)
        except XMLRPCMethodDoesNotExist as e:
            session.rollback()
            response = xmlrpclib.dumps(xmlrpclib.Fault(1,
                    'XML-RPC method %s not implemented by this server' % e.args[0]))
        except Invalid, e:
             session.rollback()
             response = xmlrpclib.dumps(xmlrpclib.Fault(1, str(e)))
        except Exception:
            session.rollback()
            log.exception('Error handling XML-RPC method')
            # Some other error; send back some error info
            response = xmlrpclib.dumps(
                xmlrpclib.Fault(1, "%s:%s" % sys.exc_info()[:2])
                )

        if str(method).startswith('auth.'):
            log.debug('Time: %s %s', datetime.utcnow() - start, str(method))
        else:
            log.debug('Time: %s %s %s', datetime.utcnow() - start, str(method), str(params)[0:50])
        cherrypy.response.headers["Content-Type"] = "text/xml"
        return response
github mediadrop / mediadrop / mediadrop / lib / decorators.py View on Github external
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.
        """
        if isinstance(self.validators, dict):
            new_params = {}
            errors = {}
            for field, validator in self.validators.iteritems():
                try:
                    new_params[field] = validator.to_python(params.get(field),
                                                            self.state)
                # catch individual validation errors into the errors dictionary
                except formencode.api.Invalid, inv:
                    errors[field] = inv

            # If there are errors, create a compound validation error based on
            # the errors dictionary, and raise it as an exception
            if errors:
                raise formencode.api.Invalid(
                    formencode.schema.format_compound_error(errors),
                    params, None, error_dict=errors)
            return new_params

        elif isinstance(self.validators, formencode.Schema):
            # A FormEncode Schema object - to_python converts the incoming
            # parameters to sanitized Python values
            return self.validators.to_python(params, self.state)

        elif isinstance(self.validators, tw.forms.InputWidget) \
github Othernet-Project / ndb-utils / ndb_utils / properties.py View on Github external
def _validate(self, value):
        if not value:
            return None
        try:
            value = unicode(value).lower()
        except TypeError:
            raise BadValueError(formencode.Invalid('Invalid value', value))

        try:
            return email_validator.to_python(value)
        except formencode.api.Invalid, err:
            raise BadValueError(err)
github ralfonso / theory / theory / controllers / main.py View on Github external
def saveconfig(self):
        """ controller to save the web-based configuration """ 
        try:
            fields = validate_custom(form.ConfigForm(), variable_decode=True)
        except formencode.api.Invalid, e:
            return form.htmlfill(self.config(use_htmlfill=False),  e)


        if fields['action'] == 'save config':
            reloadframes = 'true'
            reloadpage = 'true'

            for k in fields.keys():
                setattr(g.tc, k, fields[k])

            try:
                g.tc.commit_config()
            except:
                redirect(url('/config?error=1&type=save'))

            if len(g.genres) == 0:
github TurboGears / tg2 / tg / decorated.py View on Github external
if hasattr(validation, '_before_validate'):
            validation._before_validate(controller, params)
        
        new_params=params
        if isinstance(validation.validators, dict):
            errors = {}
            new_params = {}
            for field, validator in validation.validators.iteritems():
                try:
                    new_params[field] = validator.to_python(params.get(field))
                except formencode.api.Invalid, inv:
                    errors[field] = inv

            if errors:
                raise formencode.api.Invalid(
                    formencode.schema.format_compound_error(errors),
                    params, None, error_dict=errors)
        elif isinstance(validation.validators, formencode.Schema):
            new_params = validation.validators.to_python(params)
        elif hasattr(validation.validators, 'validate'):
            new_params = validation.validators.validate(params)


        return new_params
github TurboGears / tg2 / tg / controllers / base.py View on Github external
controller.decoration.run_hooks('before_validate', remainder,
                                            params)
            for ignore in config.get('ignore_parameters', []):
                if params.get(ignore):
                    del params[ignore]

            # Validate user input
            params = self._perform_validate(controller, params)

            pylons.c.form_values = params

            controller.decoration.run_hooks('before_call', remainder, params)
            # call controller method
            output = controller(*remainder, **dict(params))

        except formencode.api.Invalid, inv:
            controller, output = self._handle_validation_errors(controller,
                                                                remainder,
                                                                params, inv)

        # Render template
        controller.decoration.run_hooks('before_render', remainder, params,
                                        output)
        response = self._render_response(controller, output)
        controller.decoration.run_hooks('after_render', response)
        return response
github obeattie / pylons / pylons / controllers / decorated.py View on Github external
validation = getattr(controller.decoration, 'validation', None)
        if validation is None:
            return params
        
        new_params = None
        if isinstance(validation.validators, dict):
            errors = {}
            #new_params = {}
            for field, validator in validation.validators.iteritems():
                try:
                    new_params[field] = validator.to_python(params.get(field))
                except formencode.api.Invalid, inv:
                    errors[field] = inv

            if errors:
                raise formencode.api.Invalid(
                    formencode.schema.format_compound_error(errors),
                    params, None, error_dict=errors)
        elif isinstance(validation.validators, formencode.Schema):
            new_params = validation.validators.to_python(params)
        elif hasattr(validation.validators, 'validate'):
            new_params = validation.validators.validate(params)

        if new_params is None:
            return params
        return new_params