|
| 1 | +# import getpass |
| 2 | +import pprint |
| 3 | +from collections.abc import Mapping |
| 4 | + |
| 5 | +import httpx |
| 6 | + |
| 7 | + |
| 8 | +class RequestParameterError(Exception): ... |
| 9 | + |
| 10 | + |
| 11 | +class HTTPRequestError(httpx.RequestError): ... |
| 12 | + |
| 13 | + |
| 14 | +class HTTPClientError(httpx.HTTPStatusError): ... |
| 15 | + |
| 16 | + |
| 17 | +class HTTPServerError(httpx.HTTPStatusError): ... |
| 18 | + |
| 19 | + |
| 20 | +class RequestTimeoutError(TimeoutError): |
| 21 | + def __init__(self, msg, request): |
| 22 | + msg = f"Request timeout: {msg}" |
| 23 | + self.request = request |
| 24 | + super().__init__(msg) |
| 25 | + |
| 26 | + |
| 27 | +class RequestFailedError(Exception): |
| 28 | + def __init__(self, request, response): |
| 29 | + msg = response.get("msg", "") if isinstance(response, Mapping) else str(response) |
| 30 | + msg = msg or "(no error message)" |
| 31 | + msg = f"Request failed: {msg}" |
| 32 | + self.request = request |
| 33 | + self.response = response |
| 34 | + super().__init__(msg) |
| 35 | + |
| 36 | + |
| 37 | +class _SaveRestoreAPI_Base: |
| 38 | + RequestParameterError = RequestParameterError |
| 39 | + RequestTimeoutError = RequestTimeoutError |
| 40 | + RequestFailedError = RequestFailedError |
| 41 | + HTTPRequestError = HTTPRequestError |
| 42 | + HTTPClientError = HTTPClientError |
| 43 | + HTTPServerError = HTTPServerError |
| 44 | + |
| 45 | + def __init__(self, *, base_url, timeout, request_fail_exceptions=True): |
| 46 | + self._base_url = base_url |
| 47 | + self._timeout = timeout |
| 48 | + self._client = None |
| 49 | + self._root_node_uid = "44bef5de-e8e6-4014-af37-b8f6c8a939a2" |
| 50 | + self._auth = None |
| 51 | + |
| 52 | + @property |
| 53 | + def ROOT_NODE_UID(self): |
| 54 | + return self._root_node_uid |
| 55 | + |
| 56 | + @staticmethod |
| 57 | + def gen_auth(username, password): |
| 58 | + return httpx.BasicAuth(username=username, password=password) |
| 59 | + |
| 60 | + def set_auth(self, *, username, password): |
| 61 | + self._auth = self.gen_auth(username=username, password=password) |
| 62 | + |
| 63 | + # def set_username_password(self, username=None, password=None): |
| 64 | + # if not isinstance(username, str): |
| 65 | + # print("Username: ", end="") |
| 66 | + # username = input() |
| 67 | + # if not isinstance(password, str): |
| 68 | + # password = getpass.getpass() |
| 69 | + |
| 70 | + # self._username = username |
| 71 | + # self._password = password |
| 72 | + |
| 73 | + # # TODO: rewrite the logic in this function |
| 74 | + # def _check_response(self, *, request, response): |
| 75 | + # """ |
| 76 | + # Check if response is a dictionary and has ``"success": True``. Raise an exception |
| 77 | + # if the request is considered failed and exceptions are allowed. If response is |
| 78 | + # a dictionary and contains no ``"success"``, then it is considered successful. |
| 79 | + # """ |
| 80 | + # if self._request_fail_exceptions: |
| 81 | + # # The response must be a list or a dictionary. If the response is a dictionary |
| 82 | + # # and the key 'success': False, then consider the request failed. If there |
| 83 | + # # is not 'success' key, then consider the request successful. |
| 84 | + # is_iterable = isinstance(response, Iterable) and not isinstance(response, str) |
| 85 | + # is_mapping = isinstance(response, Mapping) |
| 86 | + # if not any([is_iterable, is_mapping]) or (is_mapping and not response.get("success", True)): |
| 87 | + # raise self.RequestFailedError(request, response) |
| 88 | + |
| 89 | + def _process_response(self, *, client_response): |
| 90 | + client_response.raise_for_status() |
| 91 | + response = client_response.json() |
| 92 | + return response |
| 93 | + |
| 94 | + def _process_comm_exception(self, *, method, params, client_response): |
| 95 | + """ |
| 96 | + The function must be called from ``except`` block and returns response with an error message |
| 97 | + or raises an exception. |
| 98 | + """ |
| 99 | + try: |
| 100 | + raise |
| 101 | + |
| 102 | + except httpx.TimeoutException as ex: |
| 103 | + raise self.RequestTimeoutError(ex, {"method": method, "params": params}) from ex |
| 104 | + |
| 105 | + except httpx.RequestError as ex: |
| 106 | + raise self.HTTPRequestError(f"HTTP request error: {ex}") from ex |
| 107 | + |
| 108 | + except httpx.HTTPStatusError as exc: |
| 109 | + common_params = {"request": exc.request, "response": exc.response} |
| 110 | + if client_response and (client_response.status_code < 500): |
| 111 | + # Include more detail that httpx does by default. |
| 112 | + message = ( |
| 113 | + f"{exc.response.status_code}: " |
| 114 | + f"{exc.response.json()['detail'] if client_response.content else ''} " |
| 115 | + f"{exc.request.url}" |
| 116 | + ) |
| 117 | + raise self.HTTPClientError(message, **common_params) from exc |
| 118 | + else: |
| 119 | + raise self.HTTPServerError(exc, **common_params) from exc |
| 120 | + |
| 121 | + def _prepare_request( |
| 122 | + self, *, method, params=None, url_params=None, headers=None, data=None, timeout=None, auth=None |
| 123 | + ): |
| 124 | + kwargs = {} |
| 125 | + if params: |
| 126 | + kwargs.update({"json": params}) |
| 127 | + if url_params: |
| 128 | + kwargs.update({"params": url_params}) |
| 129 | + if headers: |
| 130 | + kwargs.update({"headers": headers}) |
| 131 | + if data: |
| 132 | + kwargs.update({"data": data}) |
| 133 | + if timeout is not None: |
| 134 | + kwargs.update({"timeout": self._adjust_timeout(timeout)}) |
| 135 | + if method != "GET": |
| 136 | + auth = auth or self._auth |
| 137 | + if auth is not None: |
| 138 | + kwargs.update({"auth": auth}) |
| 139 | + return kwargs |
| 140 | + |
| 141 | + def _prepare_login(self, *, username=None, password=None): |
| 142 | + method, url = "POST", "/login" |
| 143 | + params = {"username": username, "password": password} |
| 144 | + return method, url, params |
| 145 | + |
| 146 | + def _prepare_get_node(self, *, node_uid): |
| 147 | + method, url = "GET", f"/node/{node_uid}" |
| 148 | + return method, url |
| 149 | + |
| 150 | + def get_children(self, node_uid): |
| 151 | + return self.send_request("GET", f"/node/{node_uid}/children") |
| 152 | + |
| 153 | + def create_config(self, parent_node_uid, name, pv_list): |
| 154 | + config_dict = { |
| 155 | + "configurationNode": { |
| 156 | + "name": name, |
| 157 | + "nodeType": "CONFIGURATION", |
| 158 | + "userName": self._username, |
| 159 | + }, |
| 160 | + "configurationData": { |
| 161 | + "pvList": pv_list, |
| 162 | + }, |
| 163 | + } |
| 164 | + print(f"config_dict=\n{pprint.pformat(config_dict)}") |
| 165 | + return self.send_request("PUT", f"/config?parentNodeId={parent_node_uid}", json=config_dict) |
| 166 | + |
| 167 | + def update_config(self, node_uid, name, pv_list): |
| 168 | + config_dict = { |
| 169 | + "configurationNode": { |
| 170 | + "name": name, |
| 171 | + "nodeType": "CONFIGURATION", |
| 172 | + "userName": self._username, |
| 173 | + "uniqueId": node_uid, |
| 174 | + }, |
| 175 | + "configurationData": { |
| 176 | + "pvList": pv_list, |
| 177 | + }, |
| 178 | + } |
| 179 | + print(f"config_dict=\n{pprint.pformat(config_dict)}") |
| 180 | + # return self.send_request("POST", f"/config/{node_uid}", json=config_dict) |
| 181 | + return self.send_request("POST", "/config", json=config_dict) |
0 commit comments