1"""
2This module provides a base handler with some useful methods for all REST API handlers.
3"""
4from typing import Any
5import falcon
6
7from ..serialization import my_load_from_json, my_to_json
8
9
[docs]
10class BaseHandler():
11 """
12 Base class for all REST API handlers.
13 """
[docs]
14 def send_error(self, resp: falcon.Response, error_msg: str) -> None:
15 """
16 Sends an error message back.
17
18 Parameters
19 ----------
20 resp : `falcon.Response <https://falcon.readthedocs.io/en/stable/api/request_and_response_asgi.html#response>`_
21 Response instance.
22 error_msg : `str`
23 Error message.
24 """
25 resp.status = falcon.HTTP_BAD_REQUEST
26 resp.data = error_msg.encode()
27
[docs]
28 def send_invalid_resource_id_error(self, resp: falcon.Response) -> None:
29 """
30 Sends an error that th given resource ID (e.g. scenario ID, or SCADA data ID) is invalid.
31
32 Parameters
33 ----------
34 resp : `falcon.Response`
35 Response instance.
36 """
37 resp.status = falcon.HTTP_BAD_REQUEST
38 resp.data = "Invalid resource ID".encode()
39
[docs]
40 def send_json_parsing_error(self, resp: falcon.Response) -> None:
41 """
42 Sends an error that the JSON parsing failed.
43
44 Parameters
45 ----------
46 resp : `falcon.Response <https://falcon.readthedocs.io/en/stable/api/request_and_response_asgi.html#response>`_
47 Response instance.
48 """
49 resp.status = falcon.HTTP_BAD_REQUEST
50 resp.data = "Failed to parse JSON".encode()
51
[docs]
52 def load_json_data_from_request(self, req: falcon.Request) -> Any:
53 """
54 Loads/Parses an object from given JSON data.
55
56 Parameters
57 ----------
58 req : `falcon.Request <https://falcon.readthedocs.io/en/stable/api/request_and_response_asgi.html#request>`_
59 Request instance.
60
61 Returns
62 -------
63 `Any`
64 Loaded object.
65 """
66 try:
67 return my_load_from_json(req.bounded_stream.read())
68 except Exception:
69 return None
70
[docs]
71 def send_json_response(self, resp: falcon.Response, data: Any) -> None:
72 """
73 Sends a JSON response.
74
75 Parameters
76 ----------
77 resp : `falcon.Response <https://falcon.readthedocs.io/en/stable/api/request_and_response_asgi.html#response>`_
78 Response instance.
79 data : `Any`
80 Data to be sent.
81 """
82 resp.content_type = falcon.MEDIA_JSON
83 resp.status = falcon.HTTP_200
84 resp.data = my_to_json(data).encode()