def _validate(self, value): super()._validate(value) if not isinstance(value, bytes): raise ValidationError('Invalid input type.') if value is None or value == b'': raise ValidationError('Invalid input type.')
def normalize(self, value): result = normalize_uri_result(value) if not result.scheme: raise ValidationError( "URI scheme is required for: {}".format(value)) if not result.authority: raise ValidationError( "URI authority is required for: {}".format(value)) return result.unsplit()
def _deserialize(self, value, attr, obj, **kwargs): """ _deserialize handles multiple formats of query string parameter lists including: /foo?bars=1,2 /foo?bars[]=1&bars[]2 /foo?bars=&... and returns a list of values """ if value is None: return None if value == "": return [] try: attribute_elements = [ attr_element.split(",") for attr_element in obj.getlist(attr) ] attribute_params = [ param for attr_param in attribute_elements for param in attr_param ] return PrintableList(super()._deserialize(attribute_params, attr, obj)) except ValueError: raise ValidationError("Invalid query string list argument")
def _deserialize(self, *args, **kwargs) -> typing.Any: source_str: str = super()._deserialize(*args, **kwargs) if self._is_import(source_str): last_dot_idx = source_str.rfind(".") module_name = source_str[:last_dot_idx] object_name = source_str[last_dot_idx + 1:] return nodes.ImportableModule(callable_name=object_name, module_name=module_name) elif self._is_filepath(source_str): if source_str.startswith("/"): raise ValidationError("Only realative paths are allowed") parts = source_str.split("::") if len(parts) != 2: raise ValidationError( "Incorrect filepath format, expected example.py::ClassName" ) module_path, object_name = parts return nodes.ImportablePath(callable_name=object_name, filepath=module_path)
def _deserialize(self, value, attr, data, **kwargs): """ Deserialize value as a uuid. Handle both string and UUID object. """ if value is None: return None try: if isinstance(value, UUID): return str(value) else: return str(UUID(value)) except ValueError: raise ValidationError('Not a valid UUID.')
def _deserialize(self, value, attr, obj): """ Deserialize value as a Unix timestamp (in float seconds). Handle both numeric and UTC isoformat strings. """ if value is None: return None try: return float(value) except ValueError: parsed = parser.parse(value) if parsed.tzinfo: if parsed.utcoffset().total_seconds(): raise ValidationError("Timestamps must be defined in UTC") parsed = parsed.replace(tzinfo=None) return (parsed - TimestampField.EPOCH).total_seconds()
def generate_lambda(user_submitted_string): # make a list of safe functions safe_list = ["math", "lambda"] # use the list to filter the local namespace safe_dict = dict([(k, locals().get(k, None)) for k in safe_list]) all_args = set() try: node = ast.parse(user_submitted_string, mode="eval") except TypeError: raise ValidationError( "No value was passed in as a function as a constraint.") except SyntaxError: raise ValidationError( f'No parsable lambda was detected. Try it yourself: `ast.parse({user_submitted_string}, mode="eval")`' ) for elem in ast.walk(node): if isinstance(elem, ast.Name): all_args.update(str(elem.id)) if len(all_args) > 1: raise ValidationError( f"Only one variable ('x') is supported in lambda constraints at this time. The following variables were detected: '{','.join(all_args)}'" ) if len(all_args) == 0: raise ValidationError( f"No variables were detected in the lambda constraint: '{user_submitted_string}'" ) if list(all_args)[0] != "x": raise ValidationError( f"Only the variable 'x' is supported at this time. The following variables were detected: '{','.join(all_args)}'" ) lambda_string = f"lambda {','.join(all_args)}: {user_submitted_string}" return_lambda = eval(lambda_string, {"__builtins__": None}, safe_dict) if lambda_string is None: raise ValidationError( 'Could not parse %s into a lambda with one variable. Test yourself by running this on the command line: \ \'eval(%s, {"__builtins__": None}, %s' % user_submitted_string, lambda_string, str(safe_dict), ) else: return return_lambda