Passed
Push — upgrade-to-connexion3 ( 5f0222...e1e5d5 )
by Juho
10:49
created

annif.openapi.validation   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 26
dl 0
loc 40
rs 10
c 0
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A CustomRequestBodyValidator._validate() 0 16 4
A CustomRequestBodyValidator.__init__() 0 2 1
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