async def exception_middleware(request: web.Request, handler: Callable) -> web.Response: """ Обрабатывает исключения приложения :param request: объект запроса :param handler: обработчик :return: объект ответа """ try: response: web.Response = await handler(request) return response except MarshmallowValidationError as ex: exc = exceptions.ValidationError(debug=str(ex), message=exceptions.ValidationError.message) except exceptions.BaseAppException as ex: exc = ex except web_exceptions.HTTPBadRequest as ex: exc = exceptions.InputValidationError(debug=ex.text, message=exceptions.InputValidationError.message) except web_exceptions.HTTPUnprocessableEntity as ex: exc = exceptions.ValidationError(debug=ex.text, message=exceptions.ValidationError.message) except web_exceptions.HTTPForbidden as ex: exc = exceptions.Forbidden(debug=f'Goodbye Moonmen. {ex}', message=exceptions.Forbidden.message) except web_exceptions.HTTPNotFound as ex: exc = exceptions.NotFound(debug=ex.text, message=exceptions.NotFound.message) except Exception as ex: # pylint: disable=broad-except exc = exceptions.ServerError(debug=str(ex), message=exceptions.ServerError.message) exc_data = exc.as_dict() exc_data['message'] = exc.message exc_data.pop('code', None) exc.__init__(**exc_data) return web.json_response(exc.as_dict(), status=exc.status_code)
def is_valid_division(self, tree): if not type(tree) is self.treetype: raise exceptions.ValidationError('Type mismatch: ' + str(type(tree)) + ' is not ' + str(self.treetype) + '.') if not tree.data == 'division': return False if not tree.children[0].data == 'number': raise exceptions.ValidationError('Tree prefix incorrect: ' + str(tree.data) + ' given, number expected.') if not tree.children[1].data == 'number': raise exceptions.ValidationError('Tree prefix incorrect: ' + str(tree.data) + ' given, number expected.') if not len(tree.children) == 2: raise exceptions.SemanticError('2 children expected, ' + len(tree.children[0].children) + ' given.') if not int(tree.children[0].children[0].value) > 0: raise exceptions.SemanticError('Positive/nonzero value needed for division numerator.') denom = int(tree.children[1].children[0].value) validDenoms = [1, 2, 4, 8, 16, 32, 64, 128] if denom not in validDenoms: raise exceptions.DivisionError('Division denominator must be power of 2.') return True
def validate_patterns_are_files(patterns, check_size=True): """ Check that a list of `patterns` are valid files. Arguments: patterns (list): a list of patterns to be check. check_size (bool): check size is not zero for all files matched. Returns: bool: True if all patterns match existing files. """ for pattern in patterns: files = list(glob(pattern)) if not files: msg = "{} pattern matched no files.".format(pattern) raise exceptions.ValidationError(msg) for i in files: if not os.path.isfile(i): msg = "{} is not a file.".format(i) raise exceptions.ValidationError(msg) if check_size and not os.path.getsize(i) > 0: msg = "{} is an empty file.".format(i) raise exceptions.ValidationError(msg) return True
def _validate_event_name(self, event): if event == '' and self.event == '': msg = "You must specify an event name to show sets for a tournament" raise exceptions.ValidationError(msg) if event == '': event = self.event return event
def is_valid_identifier(self, tree): if not type(tree) is self.treetype: raise exceptions.ValidationError('Type mismatch: ' + str(type(tree)) + ' is not ' + str(self.treetype) + '.') if not tree.data == 'id': return False theID = tree.children[0] length = len(theID) if length < 2: raise exceptions.SemanticError('At least 2 children expected, ' + len(tree.children[0].children) + ' given.') if theID[0] != '$': raise exceptions.SemanticError('Identifier must begin with \'$\'') if not theID[1].isalpha(): raise exceptions.SemanticError('Identifier first non-$ must be alpha-non-numeric.') for i in range(2, length): idChar = theID[i] if not(idChar.isalnum() or idChar == '_' or idChar == '-'): raise exceptions.SemanticError('Identifier may only contain alphanumeric, _, and -.') return True
def json_datetime_encoder(obj): if isinstance(obj, datetime.datetime): return cst(obj) if isinstance(obj, datetime.time): return str(obj) else: raise exceptions.ValidationError('Invalid object type')
def extract_colors_from_file(file, clusters=None): clusters = clusters or config.CLUSTERS if file.mimetype not in {'image/jpeg', 'image/png'}: raise exceptions.ValidationError('Invalid File Type') image = Image.open(file.stream) # Resize new_width, new_height = calculate_new_size(image) image = image.resize((new_width, new_height), Image.ANTIALIAS) img_array = np.array(image) if img_array.shape[2] > 3: img_array = img_array[:, :, :3] img_vector = img_array.reshape( (img_array.shape[0] * img_array.shape[1], 3)) # Create model model = KMeans(n_clusters=clusters) labels = model.fit_predict(img_vector) label_counts = Counter(labels) total_count = sum(label_counts.values()) hex_colors = [rgb2hex(center) for center in model.cluster_centers_] return dict(zip(hex_colors, list(label_counts.values())))
def _validate(self, model = None): # calls the event handler for the validation process this # should setup the operations for a correct validation self.pre_validate() # starts the model reference with the current model in # case none is defined model = model or self.model # retrieves the class associated with the current instance # to be able to retrieve the correct validate methods cls = self.__class__ # checks if the current model is new (create operation) # and sets the proper validation methods retrieval method is_new = self.is_new() if is_new: method = cls.validate_new else: method = cls.validate # runs the validation process on the various arguments # provided to the account and in case an error is returned # raises a validation error to the upper layers errors, object = validation.validate( method, object = model, build = False ) if errors: raise exceptions.ValidationError(errors, object) # calls the event handler for the validation process this # should finish the operations from a correct validation self.post_validate()
def is_valid_rest(self, tree): if not type(tree) is self.treetype: raise exceptions.ValidationError('Type mismatch: ' + str(type(tree)) + ' is not ' + str(self.treetype) + '.') if not tree.data == 'rest': return False return True
def is_valid_tree(self, tree): if not type(tree) is self.treetype: raise exceptions.ValidationError('Type mismatch: ' + str(type(tree)) + ' is not ' + str(self.treetype) + '.') if tree.data != 'start': return False for i in range(len(tree.children[:-1])): if tree.children[i].data == 'id': if tree.children[i+1].data != 'rhs': raise exceptions.ValidationError('Assignment right-hand side not found.') if tree.children[i].data == 'rhs': if tree.children[i-1].data != 'id': raise exceptions.ValidationError('Assignment identifier not found.') if tree.children[-1].data != 'compose': raise exceptions.SemanticError('Compose statement not found.') return True
async def exception_middleware( # pylint: disable=bad-continuation request: web.Request, handler: Callable[[web.Request], Awaitable[web.Response]], ) -> web.Response: # pylint: enable=bad-continuation """ Обрабатывает исключения приложения :param request: web.Request объект запроса :param handler: Coroutine[[web.Request], web.Response] обработчик :return: web.Response объект ответа """ exc: Optional[exceptions.ServerError] = None try: response: web.Response = await handler(request) except exceptions.ServerError as ex: exc = ex except MarshmallowValidationError as ex: exc = exceptions.ValidationError( debug=str(ex), message=exceptions.ValidationError.message) except web_exceptions.HTTPBadRequest as ex: exc = exceptions.InputValidationError( debug=ex.text, message=exceptions.InputValidationError.message) except web_exceptions.HTTPUnprocessableEntity as ex: exc = exceptions.ValidationError( debug=ex.text, message=exceptions.ValidationError.message) except web_exceptions.HTTPForbidden as ex: exc = exceptions.Forbidden(debug=f'Goodbye Moonmen. {ex}', message=exceptions.Forbidden.message) except web_exceptions.HTTPNotFound as ex: exc = exceptions.NotFound(debug=ex.text, message=exceptions.NotFound.message) except Exception as ex: # pylint: disable=broad-except exc = exceptions.ServerError(debug=str(ex), message=exceptions.ServerError.message) if not exc: return response exc_data = exc.as_dict() exc_data['message'] = exc.message exc_data.pop('code', None) type(exc)(**exc_data) return web.json_response(exc.as_dict(), status=exc.status_code)
def _validate_query_params(params, valid_params, route_type): """Validates query params for Smash.gg requests""" for param in params: if param not in valid_params: error_msg = """ '{0}' is not a valid query param for route of type: {1}. Valid types are [{2}]. """.format(param, route_type, ', '.join(valid_params)) raise exceptions.ValidationError(error_msg)
def validate_required(): """ Validate if all required flags exist. """ for flag_name, flag in iteritems(Flags.required_flags): if flag.value() is None: Flags.print_help() raise exceptions.ValidationError( 'Required flag "%s" has not been set.' % flag_name)
def is_valid_inlinedynamic(self, tree): if not type(tree) is self.treetype: raise exceptions.ValidationError('Type mismatch: ' + str(type(tree)) + ' is not ' + str(self.treetype) + '.') if tree.data != 'inlinedynamic': return False d = tree.children[0].lower() if d not in self.valid_levels: raise exceptions.DynamicError('Incorrect inline dynamic.') return True
def to_python(self, value): if value is None: return value if isinstance(value, FlexiDate): return value value = smart_str(value) if len(value) == 0: return value try: parsed = parse_flex_date(value) if parsed is not None and len(parsed.isoformat()) > 0: return parsed except ValueError: msg = self.error_messages['invalid'] % value raise exceptions.ValidationError(msg) msg = self.error_messages['invalid_date'] % value raise exceptions.ValidationError(msg)
def sets_played_by_player(bracket_id, tag): try: tag = str(tag) tag = tag.lower() except: msg = "Given player tag is not and cannot be converted into a string" raise exceptions.ValidationError(msg) uri = BRACKET_URL + str(bracket_id) response = api.get(uri, VALID_BRACKET_PARAMS) return _filter_sets_given_player(response, tag)
def verify(self, flag_values): """Verify that constraint is satisfied. flags library calls this method to verify Validator's constraint. Args: flag_values: gflags.FlagValues, containing all flags Raises: Error: if constraint is not satisfied. """ param = self._get_input_to_checker_function(flag_values) if not self.checker(param): raise exceptions.ValidationError(self.message)
def is_valid_measure(self, tree): if not type(tree) is self.treetype: raise exceptions.ValidationError('Type mismatch: ' + str(type(tree)) + ' is not ' + str(self.treetype) + '.') if not tree.data == 'measure': return False for subtree in tree.children: isInstr = self.is_valid_instrumentation(subtree) isId = self.is_valid_identifier(subtree) if (not isInstr) and (not isId): raise exceptions.MeasureError('Instrument or identifier required.') return True
async def exception_middleware( request: web.Request, handler: Callable[[web.Request], Awaitable[web.Response]], ) -> web.Response: sentry_event_id: Optional[str] = None try: response: web.Response = await handler(request) return response except MarshmallowValidationError as ex: exc: ServerError = exceptions.ValidationError(str(ex)) except web_exceptions.HTTPBadRequest as ex: exc = exceptions.InputValidationError(ex.text or '') except web_exceptions.HTTPUnprocessableEntity as ex: exc = exceptions.ValidationError(ex.text or '') except web_exceptions.HTTPForbidden as ex: exc = exceptions.Forbidden(str(ex)) except web_exceptions.HTTPNotFound as ex: exc = exceptions.NotFound(ex.text or '') except asyncio.CancelledError as ex: exc = exceptions.ServerError(str(ex)) except exceptions.ServerError as ex: exc = ex except NotImplementedError: exc = exceptions.MethodNotImplemented() # nolint except Exception as ex: # pylint: disable=W0703 print_exc() sentry_event_id = sentry_sdk.capture_exception(ex) exc = exceptions.ServerError(str(ex)) if not sentry_event_id: sentry_event_id = sentry_sdk.capture_exception(exc) return web.json_response(data=exc.as_dict(), status=exc.status_code, headers={'X-Sentry-ID': sentry_event_id or ''})
def is_valid_note(self, tree): if not type(tree) is self.treetype: raise exceptions.ValidationError('Type mismatch: ' + str(type(tree)) + ' is not ' + str(self.treetype) + '.') if tree.data != 'note': return False if len(tree.children[0].children) != 2: raise exceptions.SemanticError('2 children expected, ' + len(tree.children[0].children) + ' given.') if tree.children[0].data != 'division': raise exceptions.ValidationError('Tree prefix incorrect: ' + str(tree.data) + ' given, division expected.') if not self.is_valid_division(tree.children[0]): raise exceptions.SemanticError("Invalid Division") if type(tree.children[1]) == self.tokentype and tree.children[1].type == 'REST': return True if not self.is_valid_notename(tree.children[1]) and not self.is_valid_chord(tree.children[1]) and not self.is_valid_tuple(tree.children[1]): raise exceptions.SemanticError("Invalid notename or chord") return True
def is_valid_instrumentation(self, tree): if not type(tree) is self.treetype: raise exceptions.ValidationError('Type mismatch: ' + str(type(tree)) + ' is not ' + str(self.treetype) + '.') if tree.data != 'instrumentation': return False if len(tree.children) < 1: raise exceptions.SemanticError('At least 1 child expected, ' + len(tree.children[0].children) + ' given.') child = tree.children if type(child[0]) == self.treetype: if not self.is_valid_identifier(child[0]): return False child[0] = self.variables[child[0].children[0]] if type(child[0]) != self.tokentype: raise exceptions.ValidationError('Type mismatch: ' + str(type(child[0])) + ' is not ' + str(self.tokentype) + '.') if child[0].type != 'INSTRUMENT': raise exceptions.ValidationError('Type mismatch: ' + child[0].type + ' is not INSTRUMENT.') for x in child[1:]: if not self.is_valid_noteitem(x): raise exceptions.SemanticError('Invalid Noteitem.') return True
def validate_patterns_are_dirs(patterns): """ Check that a list of `patterns` are valid dirs. Arguments: patterns (list): a list of directory patterns. Returns: bool: True if all patterns match existing directories. """ for pattern in patterns: dirs = list(glob(pattern)) if not dirs: msg = "{} pattern matched no dirs.".format(pattern) raise exceptions.ValidationError(msg) for i in dirs: if not os.path.isdir(i): msg = "{} is not a directory.".format(i) raise exceptions.ValidationError(msg) return True
def create(self, vals): DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" from_dt = datetime.strptime(vals['date_from'], DATETIME_FORMAT) to_dt = datetime.strptime(vals['date_to'], DATETIME_FORMAT) timedelta = to_dt - from_dt diff_day = timedelta.days + float(timedelta.seconds) / 86400 if (round(math.floor(diff_day)) + 1) == 1: for o in self.env['odoo_hr.weeklyholidays'].search([]): if calendar.day_name[from_dt.weekday()] == o.day_of_week: raise exceptions.ValidationError("This day is weekend ") #for o in self.env['odoo_hr.odooholiday'].search([]): # if calendar.day_name[from_dt.weekday()]== o.start_date: # raise exceptions.ValidationError("This day is national holiday") return super(odoocheckholidays, self).create(vals)
def is_valid_dynamic(self, tree): if not type(tree) is self.treetype: raise exceptions.ValidationError('Type mismatch: ' + str(type(tree)) + ' is not ' + str(self.treetype) + '.') if tree.data != 'dynamic': return False item = tree.children[0].data if item == 'inlinedynamic': d = tree.children[0].children[0].lower() if d not in self.valid_levels: raise exceptions.DynamicError('Incorrect inline dynamic.') elif item == 'id': return Semantic.is_valid_identifier(self, tree) else: raise exceptions.SemanticError('Inline dynamic or identifier expected, not given.') return True
def is_valid_chord(self, tree): if not type(tree) is self.treetype: raise exceptions.ValidationError('Type mismatch: ' + str(type(tree)) + ' is not ' + str(self.treetype) + '.') if not tree.data == 'chord': return False try: for child in tree.children: if not child.data == 'notename': return False if not self.is_valid_notename(child): raise SemanticError except: raise exceptions.SemanticError('Chords should only contain notes.') return True
def onchange_date_to(self, cr, uid, ids, date_to, date_from): """ Update the number_of_days. """ # date_to has to be greater than date_from if (date_from and date_to) and (date_from > date_to): raise exceptions.ValidationError( " The start date must be anterior to the end date. ") result = {'value': {}} # Compute and update the number of days if (date_to and date_from) and (date_from <= date_to): diff_day = self._get_number_of_days(date_from, date_to) result['value']['total_years_create'] = round(math.floor(diff_day)) else: result['value']['total_years_create'] = 0 return result
def is_valid_notename(self, tree): if not type(tree) is self.treetype: raise exceptions.ValidationError('Type mismatch: ' + str(type(tree)) + ' is not ' + str(self.treetype) + '.') if not tree.data == 'notename': return False if not (len(tree.children) == 3 or len(tree.children) == 2): raise exceptions.SemanticError('2 or 3 children expected, ' + len(tree.children[0].children) + ' given.') n = tree.children[0] n.upper() validNoteLetters = ['A', 'B', 'C', 'D', 'E', 'F', 'G'] if n not in validNoteLetters: raise exceptions.NoteError('Invalid note letter.') if len(tree.children) == 3: #Has accidental if tree.children[1].data != 'accidental': raise exceptions.NoteError('Accidental expected, not given.') if tree.children[2].data != 'number': raise exceptions.NoteError('Octave number expected, not given') acc = tree.children[1].children[0].value if acc != '#' and acc != 'b': raise exceptions.NoteError('Incorrect accidental symbol given, \'b\' or \'#\' expected.') octave = int(tree.children[2].children[0].value) if 9 > octave < 0: raise exceptions.NoteError('Invalid note octave.') elif len(tree.children) == 2: #No accidental or rest if tree.children[1].data != 'number': raise exceptions.NoteError('Octave number expected, not given') octave = int(tree.children[1].children[0].value) if 9 > octave < 0: raise exceptions.NoteError('Invalid note octave.') else: #Invalid length raise exceptions.NoteError('Invalid note syntax') return False return True
def onchange_date_from(self, cr, uid, ids, date_to, date_from): # date_to has to be greater than date_from if (date_from and date_to) and (date_from > date_to): raise exceptions.ValidationError( "The start date must be anterior to the end date. ") result = {'value': {}} # No date_to set so far: automatically compute one 8 hours later if date_from and not date_to: date_to_with_delta = datetime.strptime(str(date_from), "%Y-%m-%d") result['value']['date_to'] = str(date_to_with_delta) # Compute and update the number of days if (date_to and date_from) and (date_from <= date_to): diff_day = self._get_number_of_days(date_from, date_to) result['value']['total_years_create'] = round(math.floor(diff_day)) else: result['value']['total_years_create'] = 0 return result
def create(name, parser_type, description, default=None, required=False): """ Create a Flag with its configurations. Args: name (str): The name of the flag. This must be unique. parser_type (flag_parsers.FlagType): The type of this flag description (str): The description of the flag. default: If not required, then it should have a default value. required (bool): Whether this flag is required or not. Returns: Flag: The object that contains flag value. """ if name in Flags.flag_registry: raise exceptions.DuplicateFlagError( 'Duplicated flag names. Flag "%s" already exists.' % name) parser = flag_parsers.get_parser(parser_type) flag = Flag(name, parser, default, description, required, module_name=Flags.get_calling_module_name()) if name in Flags.raw_flags: flag_str_value = Flags.raw_flags.get(name) flag.parse_and_set(flag_str_value) else: if Flags.is_parsed and required: Flags.flag_registry[name] = flag Flags.print_help() raise exceptions.ValidationError( 'Required flag "%s" has not been set.' % name) flag._value = default if required: Flags.required_flags[name] = flag Flags.flag_registry[name] = flag return flag
def is_valid_noteitem(self, tree): if not type(tree) is self.treetype: raise exceptions.ValidationError('Type mismatch: ' + str(type(tree)) + ' is not ' + str(self.treetype) + '.') if not tree.data == 'noteitem': return False if not len(tree.children) == 1: raise exceptions.SemanticError('1 child expected, ' + len(tree.children[0].children) + ' given.') item = tree.children[0].data if item == 'note': return Semantic.is_valid_note(self, tree.children[0]) elif item == 'id': return Semantic.is_valid_identifier(self, tree.children[0]) elif item == 'inlinedynamic': d = tree.children[0].children[0].lower() if d not in self.valid_levels: raise exceptions.DynamicError('Incorrect inline dynamic.') else: raise exceptions.SemanticError('Note, inline dynamic, or identifier expected, not given.') return True