AAS HTTP Client Documentation
Loading...
Searching...
No Matches
http_helper.py
Go to the documentation of this file.
1"""Helper methods for HTTP operations."""
2
3import json
4import logging
5
6from requests.models import Response
7
8_logger = logging.getLogger(__name__)
9
10STATUS_CODE_200 = 200
11STATUS_CODE_201 = 201
12STATUS_CODE_202 = 202
13STATUS_CODE_204 = 204
14STATUS_CODE_404 = 404
17def log_response(response: Response, log_level: int = logging.ERROR): # noqa: C901, PLR0912
18 """Extracts and logs error messages from an HTTP response.
19
20 This method parses the response content for error details, messages, or error fields,
21 and logs each error message found. If the response cannot be decoded as JSON,
22 it logs the raw response content. Always logs the HTTP status code.
23
24 :param response: The HTTP response object to extract and log errors from
25 :param log_level: The logging level to use (default is logging.ERROR)
26 """
27 result_error_messages: list[str] = []
28
29 try:
30 response_content_dict: dict = json.loads(response.content)
31
32 if "detail" in response_content_dict:
33 detail: dict = response_content_dict.get("detail", {})
34 if "error" in detail:
35 error: str = detail.get("error", "")
36 result_error_messages.append(f"{error}")
37 else:
38 result_error_messages.append(f"{detail}")
39
40 elif "messages" in response_content_dict or "Messages" in response_content_dict:
41 messages: list = response_content_dict.get("messages", [])
42
43 if not messages:
44 messages = response_content_dict.get("Messages", [])
45
46 for message in messages:
47 if isinstance(message, dict) and "message" in message:
48 result_error_messages.append(message["message"])
49 else:
50 result_error_messages.append(str(message))
51 elif "error" in response_content_dict:
52 result_error_messages.append(response_content_dict.get("error", ""))
53
54 if len(result_error_messages) == 0 and response.text:
55 result_error_messages.append(response.text)
56
57 except json.JSONDecodeError:
58 if response.content and response.content != "b''":
59 result_error_messages.append(str(response.content))
60
61 _logger.log(log_level, f"Status code: {response.status_code}")
62 for result_error_message in result_error_messages:
63 _logger.log(log_level, result_error_message)
64
65 _logger.debug(f"Full response content: {str(response.content)}")