Skip to content

Commit

Permalink
Adding custom ParameterValidator to Connexion setup
Browse files Browse the repository at this point in the history
CLOUDBLD-12516

Signed-off-by: Felipe de Almeida <[email protected]>
  • Loading branch information
fepas authored and taylormadore committed Mar 9, 2023
1 parent b0b0fb5 commit a90663e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
4 changes: 2 additions & 2 deletions cachito/web/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from cachito.web.docs import docs
from cachito.web.errors import json_error, validation_error
from cachito.web.metrics import init_metrics
from cachito.web.validation import RequestBodyValidator
from cachito.web.validation import ParameterValidator, RequestBodyValidator


def healthcheck():
Expand Down Expand Up @@ -118,7 +118,7 @@ def create_app(config_obj=None):
connexion_app.add_api(
f"{path}/static/api_v1.yaml",
strict_validation=True,
validator_map={"body": RequestBodyValidator},
validator_map={"body": RequestBodyValidator, "parameter": ParameterValidator},
)

app.add_url_rule("/healthcheck", view_func=healthcheck)
Expand Down
24 changes: 24 additions & 0 deletions cachito/web/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import jsonschema
from connexion import decorators
from connexion.exceptions import BadRequestProblem, ExtraParameterProblem

from cachito.errors import ValidationError

Expand Down Expand Up @@ -70,3 +71,26 @@ def validate_schema(self, data, url):
raise ValidationError(exception.message)

return None


class ParameterValidator(decorators.validation.ParameterValidator):
"""
Changes the default Connexion exception to Cachito's ValidationError.
For more information about custom validation error handling:
- https://github.com/zalando/connexion/issues/558
- https://connexion.readthedocs.io/en/latest/request.html
"""

def __call__(self, function):
"""Throw cachito.ValidationError."""
wrapper = super().__call__(function)

def handle_wrapper(request):
"""Handle original wrapper."""
try:
return wrapper(request)
except (BadRequestProblem, ExtraParameterProblem) as exception:
raise ValidationError(exception.detail)

return handle_wrapper

0 comments on commit a90663e

Please sign in to comment.