|
| 1 | +""" Parses and validation aiohttp requests against pydantic models |
| 2 | +
|
| 3 | +These functions are analogous to `pydantic.tools.parse_obj_as(model_class, obj)` for aiohttp's requests |
| 4 | +""" |
| 5 | + |
| 6 | +from contextlib import contextmanager |
| 7 | +from typing import Iterator, Type, TypeVar |
| 8 | + |
| 9 | +from aiohttp import web |
| 10 | +from pydantic import BaseModel, ValidationError |
| 11 | + |
| 12 | +from ..json_serialization import json_dumps |
| 13 | +from ..mimetype_constants import MIMETYPE_APPLICATION_JSON |
| 14 | + |
| 15 | +ModelType = TypeVar("ModelType", bound=BaseModel) |
| 16 | + |
| 17 | + |
| 18 | +@contextmanager |
| 19 | +def handle_validation_as_http_error( |
| 20 | + *, error_msg_template: str, resource_name: str, use_error_v1: bool |
| 21 | +) -> Iterator[None]: |
| 22 | + """ |
| 23 | + Transforms ValidationError into HTTP error |
| 24 | + """ |
| 25 | + try: |
| 26 | + |
| 27 | + yield |
| 28 | + |
| 29 | + except ValidationError as err: |
| 30 | + details = [ |
| 31 | + { |
| 32 | + "loc": ".".join(map(str, e["loc"])), |
| 33 | + "msg": e["msg"], |
| 34 | + "type": e["type"], |
| 35 | + } |
| 36 | + for e in err.errors() |
| 37 | + ] |
| 38 | + reason_msg = error_msg_template.format( |
| 39 | + failed=", ".join(d["loc"] for d in details) |
| 40 | + ) |
| 41 | + |
| 42 | + if use_error_v1: |
| 43 | + # NOTE: keeps backwards compatibility until ligher error response is implemented in the entire API |
| 44 | + # Implements servicelib.aiohttp.rest_responses.ErrorItemType |
| 45 | + errors = [ |
| 46 | + { |
| 47 | + "code": e["type"], |
| 48 | + "message": e["msg"], |
| 49 | + "resource": resource_name, |
| 50 | + "field": e["loc"], |
| 51 | + } |
| 52 | + for e in details |
| 53 | + ] |
| 54 | + error_str = json_dumps( |
| 55 | + {"error": {"status": web.HTTPBadRequest.status_code, "errors": errors}} |
| 56 | + ) |
| 57 | + else: |
| 58 | + # NEW proposed error for https://github.com/ITISFoundation/osparc-simcore/issues/443 |
| 59 | + error_str = json_dumps( |
| 60 | + { |
| 61 | + "error": { |
| 62 | + "msg": reason_msg, |
| 63 | + "resource": resource_name, # optional |
| 64 | + "details": details, # optional |
| 65 | + } |
| 66 | + } |
| 67 | + ) |
| 68 | + |
| 69 | + raise web.HTTPBadRequest( |
| 70 | + reason=reason_msg, |
| 71 | + text=error_str, |
| 72 | + content_type=MIMETYPE_APPLICATION_JSON, |
| 73 | + ) |
| 74 | + |
| 75 | + |
| 76 | +# NOTE: |
| 77 | +# |
| 78 | +# - parameters in the path are part of the resource name and therefore are required |
| 79 | +# - parameters in the query are typically extra options like flags or filter options |
| 80 | +# - body holds the request data |
| 81 | +# |
| 82 | + |
| 83 | + |
| 84 | +def parse_request_path_parameters_as( |
| 85 | + parameters_schema: Type[ModelType], |
| 86 | + request: web.Request, |
| 87 | + *, |
| 88 | + use_enveloped_error_v1: bool = True, |
| 89 | +) -> ModelType: |
| 90 | + """Parses path parameters from 'request' and validates against 'parameters_schema' |
| 91 | +
|
| 92 | + :raises HTTPBadRequest if validation of parameters fail |
| 93 | + """ |
| 94 | + with handle_validation_as_http_error( |
| 95 | + error_msg_template="Invalid parameter/s '{failed}' in request path", |
| 96 | + resource_name=request.rel_url.path, |
| 97 | + use_error_v1=use_enveloped_error_v1, |
| 98 | + ): |
| 99 | + data = dict(request.match_info) |
| 100 | + return parameters_schema.parse_obj(data) |
| 101 | + |
| 102 | + |
| 103 | +def parse_request_query_parameters_as( |
| 104 | + parameters_schema: Type[ModelType], |
| 105 | + request: web.Request, |
| 106 | + *, |
| 107 | + use_enveloped_error_v1: bool = True, |
| 108 | +) -> ModelType: |
| 109 | + """Parses query parameters from 'request' and validates against 'parameters_schema' |
| 110 | +
|
| 111 | + :raises HTTPBadRequest if validation of queries fail |
| 112 | + """ |
| 113 | + |
| 114 | + with handle_validation_as_http_error( |
| 115 | + error_msg_template="Invalid parameter/s '{failed}' in request query", |
| 116 | + resource_name=request.rel_url.path, |
| 117 | + use_error_v1=use_enveloped_error_v1, |
| 118 | + ): |
| 119 | + data = dict(request.query) |
| 120 | + return parameters_schema.parse_obj(data) |
| 121 | + |
| 122 | + |
| 123 | +async def parse_request_body_as( |
| 124 | + model_schema: Type[ModelType], |
| 125 | + request: web.Request, |
| 126 | + *, |
| 127 | + use_enveloped_error_v1: bool = True, |
| 128 | +) -> ModelType: |
| 129 | + """Parses and validates request body against schema |
| 130 | +
|
| 131 | + :raises HTTPBadRequest |
| 132 | + """ |
| 133 | + with handle_validation_as_http_error( |
| 134 | + error_msg_template="Invalid field/s '{failed}' in request body", |
| 135 | + resource_name=request.rel_url.path, |
| 136 | + use_error_v1=use_enveloped_error_v1, |
| 137 | + ): |
| 138 | + body = await request.json() |
| 139 | + return model_schema.parse_obj(body) |
0 commit comments