]> git.mxchange.org Git - fba.git/blob - fba/helpers/json.py
Continued:
[fba.git] / fba / helpers / json.py
1 # Fedi API Block - An aggregator for fetching blocking data from fediverse nodes
2 # Copyright (C) 2023 Free Software Foundation
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published
6 # by the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
16
17 import logging
18
19 import json
20 import requests
21
22 logging.basicConfig(level=logging.INFO)
23 logger = logging.getLogger(__name__)
24
25 def from_response(response: requests.models.Response) -> any:
26     logger.debug("response[]='%s' - CALLED!", type(response))
27     if not isinstance(response, requests.models.Response):
28         raise ValueError(f"Parameter response[]='{type(response)}' is not type of 'Response'")
29     elif not response.ok or response.status_code > 200:
30         raise ValueError(f"response.ok='{response.ok}',response.status_code={response.status_code},response.reason='{response.reason}' but function was invoked")
31     elif response.text.strip() != "" and response.headers.get("content-type") is not None and response.headers.get("content-type").split(";")[0] not in ["*/*", "application/json", "application/jrd+json", "application/activity+json"]:
32         logger.warning("response.headers[content-type]='%s' is not a JSON type, below json() invocation may raise an exception", response.headers.get("content-type"))
33
34     data = list()
35     if response.text.strip() != "":
36         logger.debug("response.text()=%d is not empty, invoking response.json() ...", len(response.text))
37         try:
38             data = response.json()
39
40             logger.debug("data[]='%s' - EXIT!", type(data))
41             if not isinstance(data, list) and not isinstance(data, dict):
42                 logger.warning("data[]='%s' is not wanted, wrapping into 'dict'", type(data))
43                 data = {data}
44
45         except json.decoder.JSONDecodeError as exception:
46             logger.warning("Exception '%s' during decoding JSON from response.url='%s'", type(exception), response.url)
47
48     logger.debug("data[]='%s' - EXIT!", type(data))
49     return data