| Total Complexity | 5 |
| Total Lines | 40 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | """Custom validator for the Annif API.""" |
||
| 2 | |||
| 3 | from __future__ import annotations |
||
| 4 | |||
| 5 | import logging |
||
| 6 | from typing import Any |
||
| 7 | |||
| 8 | from connexion.exceptions import BadRequestProblem |
||
| 9 | from connexion.json_schema import format_error_with_path |
||
| 10 | from connexion.validators import JSONRequestBodyValidator |
||
| 11 | from jsonschema.exceptions import ValidationError |
||
| 12 | |||
| 13 | logger = logging.getLogger("openapi.validation") |
||
| 14 | |||
| 15 | |||
| 16 | class CustomRequestBodyValidator(JSONRequestBodyValidator): |
||
| 17 | """Custom request body validator that overrides the default error message for the |
||
| 18 | 'maxItems' validator for the 'documents' property to prevent logging request body |
||
| 19 | with the contents of all documents.""" |
||
| 20 | |||
| 21 | def __init__(self, *args, **kwargs) -> None: |
||
| 22 | super().__init__(*args, **kwargs) |
||
| 23 | |||
| 24 | def _validate(self, body: Any) -> dict | None: |
||
| 25 | try: |
||
| 26 | return self._validator.validate(body) |
||
| 27 | except ValidationError as exception: |
||
| 28 | if exception.validator == "maxItems" and list(exception.schema_path) == [ |
||
| 29 | "properties", |
||
| 30 | "documents", |
||
| 31 | "maxItems", |
||
| 32 | ]: |
||
| 33 | exception.message = "too many items" |
||
| 34 | error_path_msg = format_error_with_path(exception=exception) |
||
| 35 | logger.error( |
||
| 36 | f"Validation error: {exception.message}{error_path_msg}", |
||
| 37 | extra={"validator": "body"}, |
||
| 38 | ) |
||
| 39 | raise BadRequestProblem(detail=f"{exception.message}{error_path_msg}") |
||
| 40 |