1- """Utils to check, convert and compose server responses for the RESTApi"""
2-
3- import inspect
41from typing import Any
52
6- from aiohttp import web , web_exceptions
7- from aiohttp .web_exceptions import HTTPError , HTTPException
3+ from aiohttp import web
4+ from aiohttp .web_exceptions import HTTPError
85from common_library .error_codes import ErrorCodeStr
96from common_library .json_serialization import json_dumps
107from models_library .rest_error import ErrorGet , ErrorItemType
@@ -23,36 +20,17 @@ def wrap_as_envelope(
2320 return {"data" : data , "error" : error }
2421
2522
26- # RESPONSES FACTORIES -------------------------------
27-
28-
29- def create_data_response (
30- data : Any , * , skip_internal_error_details = False , status = HTTP_200_OK
31- ) -> web .Response :
32- response = None
33- try :
34- payload = wrap_as_envelope (data ) if not is_enveloped (data ) else data
35-
36- response = web .json_response (payload , dumps = json_dumps , status = status )
37- except (TypeError , ValueError ) as err :
38- response = exception_to_response (
39- create_http_error (
40- [
41- err ,
42- ],
43- str (err ),
44- web .HTTPInternalServerError ,
45- skip_internal_error_details = skip_internal_error_details ,
46- )
47- )
48- return response
23+ def create_data_response (data : Any , * , status : int = HTTP_200_OK ) -> web .Response :
24+ enveloped_payload = wrap_as_envelope (data ) if not is_enveloped (data ) else data
25+ return web .json_response (enveloped_payload , dumps = json_dumps , status = status )
4926
5027
5128def create_http_error (
5229 errors : list [Exception ] | Exception ,
53- reason : str | None = None ,
30+ error_message : str | None = None ,
5431 http_error_cls : type [HTTPError ] = web .HTTPInternalServerError ,
5532 * ,
33+ status_reason : str | None = None ,
5634 skip_internal_error_details : bool = False ,
5735 error_code : ErrorCodeStr | None = None ,
5836) -> HTTPError :
@@ -64,14 +42,16 @@ def create_http_error(
6442 if not isinstance (errors , list ):
6543 errors = [errors ]
6644
67- is_internal_error : bool = http_error_cls == web .HTTPInternalServerError
68- default_message = reason or get_code_description (http_error_cls .status_code )
45+ is_internal_error = bool (http_error_cls == web .HTTPInternalServerError )
46+
47+ status_reason = status_reason or get_code_description (http_error_cls .status_code )
48+ error_message = error_message or status_reason
6949
7050 if is_internal_error and skip_internal_error_details :
7151 error = ErrorGet .model_validate (
7252 {
7353 "status" : http_error_cls .status_code ,
74- "message" : default_message ,
54+ "message" : error_message ,
7555 "support_id" : error_code ,
7656 }
7757 )
@@ -81,7 +61,7 @@ def create_http_error(
8161 {
8262 "errors" : items , # NOTE: deprecated!
8363 "status" : http_error_cls .status_code ,
84- "message" : default_message ,
64+ "message" : error_message ,
8565 "support_id" : error_code ,
8666 }
8767 )
@@ -92,7 +72,7 @@ def create_http_error(
9272 )
9373
9474 return http_error_cls (
95- reason = safe_status_message (reason ),
75+ reason = safe_status_message (status_reason ),
9676 text = json_dumps (
9777 payload ,
9878 ),
@@ -112,24 +92,6 @@ def exception_to_response(exc: HTTPError) -> web.Response:
11292 )
11393
11494
115- # Inverse map from code to HTTPException classes
116- def _collect_http_exceptions (exception_cls : type [HTTPException ] = HTTPException ):
117- def _pred (obj ) -> bool :
118- return (
119- inspect .isclass (obj )
120- and issubclass (obj , exception_cls )
121- and getattr (obj , "status_code" , 0 ) > 0
122- )
123-
124- found : list [tuple [str , Any ]] = inspect .getmembers (web_exceptions , _pred )
125- assert found # nosec
126-
127- http_statuses = {cls .status_code : cls for _ , cls in found }
128- assert len (http_statuses ) == len (found ), "No duplicates" # nosec
129-
130- return http_statuses
131-
132-
13395def safe_status_message (message : str | None , max_length : int = 50 ) -> str | None :
13496 """
13597 Truncates a status-message (i.e. `reason` in HTTP errors) to a maximum length, replacing newlines with spaces.
0 commit comments