def __init__(self, schema, msg, cls=None): if cls and not issubclass(cls, er.Invalid): raise er.SchemaError("Msg can only use subclases of" " Invalid as custom class") self._schema = schema self.schema = Schema(schema) self.msg = msg self.cls = cls
def message(default=None, cls=None): """Convenience decorator to allow functions to provide a message. Set a default message: >>> @message('not an integer') ... def isint(v): ... return int(v) >>> validate = Schema(isint()) >>> with raises(er.MultipleInvalid, 'not an integer'): ... validate('a') The message can be overridden on a per validator basis: >>> validate = Schema(isint('bad')) >>> with raises(er.MultipleInvalid, 'bad'): ... validate('a') The class thrown too: >>> class IntegerInvalid(er.Invalid): pass >>> validate = Schema(isint('bad', clsoverride=IntegerInvalid)) >>> try: ... validate('a') ... except er.MultipleInvalid as e: ... assert isinstance(e.errors[0], IntegerInvalid) """ if cls and not issubclass(cls, er.Invalid): raise er.SchemaError( "message can only use subclases of Invalid as custom class") def decorator(f): @wraps(f) def check(msg=None, clsoverride=None): @wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) except ValueError: raise (clsoverride or cls or er.ValueInvalid)(msg or default or 'invalid value') return wrapper return check return decorator
def _compile(self, schema): if schema is Extra: return lambda _, v: v if schema is Self: return lambda p, v: self._compiled(p, v) elif hasattr(schema, "__morphology_compile__"): return schema.__morphology_compile__(self) if isinstance(schema, Object): return self._compile_object(schema) if isinstance(schema, collections.Mapping): return self._compile_dict(schema) elif isinstance(schema, list): return self._compile_list(schema) elif isinstance(schema, tuple): return self._compile_tuple(schema) type_ = type(schema) if inspect.isclass(schema): type_ = schema if type_ in (bool, bytes, int, long, str, unicode, float, complex, object, list, dict, type(None)) or callable(schema): return _compile_scalar(schema) raise er.SchemaError('unsupported schema data type %r' % type(schema).__name__)
def Extra(_): """Allow keys in the data that are not present in the schema.""" raise er.SchemaError('"Extra" should never be called')
def Self(): raise er.SchemaError('"Self" should never be called')