Debian Codegraph @

ibm_cloud_sdk_core/detailed_response.py

raw
1 # coding: utf-8
2
3 # Copyright 2019 IBM All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 import json
18 from typing import Dict, Optional, Union
19
20 import requests
21
22
23 class DetailedResponse:
24 """Custom class for detailed response returned from APIs.
25
26 Keyword Args:
27 response: The response to the service request, defaults to None.
28 headers: The headers of the response, defaults to None.
29 status_code: The status code of the response, defaults to None.
30
31 Attributes:
32 result (dict, requests.Response, None): The response to the service request.
33 headers (dict): The headers of the response.
34 status_code (int): The status code of the response.
35
36 """
37
38 def __init__(
39 self,
40 *,
41 response: Optional[Union[dict, requests.Response]] = None,
42 headers: Optional[Dict[str, str]] = None,
43 status_code: Optional[int] = None,
44 ) -> None:
45 self.result = response
46 self.headers = headers
47 self.status_code = status_code
48
49 def get_result(self) -> Optional[Union[dict, requests.Response]]:
50 """Get the response returned by the service request.
51
52 Returns:
53 The response to the service request. This could be one of the following:
54 1. a dict that represents an instance of a response model
55 2. a requests.Response instance if the operation returns a streamed response
56 3. None if the server returned no response body
57 """
58 return self.result
59
60 def get_headers(self) -> Optional[dict]:
61 """The HTTP response headers of the service request.
62
63 Returns:
64 A dictionary of response headers or None if no headers are present.
65 """
66 return self.headers
67
68 def get_status_code(self) -> Union[int, None]:
69 """The HTTP status code of the service request.
70
71 Returns:
72 The status code associated with the service request.
73 """
74 return self.status_code
75
76 def _to_dict(self) -> dict:
77 _dict = {}
78 if hasattr(self, 'result') and self.result is not None:
79 _dict['result'] = self.result if isinstance(self.result, (dict, list)) else 'HTTP response'
80 if hasattr(self, 'headers') and self.headers is not None:
81 _dict['headers'] = self.headers
82 if hasattr(self, 'status_code') and self.status_code is not None:
83 _dict['status_code'] = self.status_code
84 return _dict
85
86 def __str__(self) -> str:
87 return json.dumps(self._to_dict(), indent=4, default=lambda o: o.__dict__)