gpkgstatus.utils.json_file_reader API documentation

# gpkgstatus.utils.json_file_reader

A JSON File Reader module that searches for given keys.

The module searches a JSON File from a given path for specific keys and stores their values for further processing or output.

###### Raises:

- FileNotFoundException: Manual Exception class that is raised if file doesn't exist or given path is not a file path.

View Source

      1"""A JSON File Reader module that searches for given keys.
      2
      3The module searches a JSON File from a given path for
      4specific keys and stores their values for further
      5processing or output.
      6
      7Raises:
      8    FileNotFoundException: Manual Exception class that is raised if \
      9            file doesn't exist or given path is not a file path.
     10
     11"""
     12import logging
     13import os
     14import sys
     15
     16from json import load as jsonload
     17from pathlib import Path
     18from tempfile import gettempdir
     19from time import time
     20from typing import Union
     21
     22from termcolor import colored
     23
     24
     25class FileNotFoundException(Exception):
     26    """Returns FileNotFoundException if file doesn't exist.
     27
     28    This exception is created for manually raising exceptions
     29    if file doesn't exist or given path is not a file path.
     30    These exceptions are handled manually as group.
     31    """
     32
     33
     34class JSONFileReader:
     35    """A Custom JSON File Reader class created using requests package.
     36
     37    The class is initialized by a JSON file path (which can be a Path object
     38    or str) and a list of keys to be searched for.
     39
     40    Raises:
     41        FileNotFoundException: Manual Exception class that is raised if \
     42            file doesn't exist or given path is not a file path.
     43    """
     44
     45    _keys: list = []
     46    _path: Union[Path, str] = Path()
     47
     48    def __init__(self, _path: Union[Path, str], *_keys):
     49        if len(_keys) < 1:
     50            print(colored("Error: At least one key is required"))
     51            sys.exit(1)
     52
     53        if not isinstance(_path, Path):
     54            _path = Path(os.path.join(gettempdir(), _path))
     55            logging.info("Path created")
     56
     57            logging.debug("Path created using filename")
     58
     59        else:
     60            logging.debug("Path was directly given")
     61
     62        if not (_path.exists() and _path.is_file()):
     63            raise FileNotFoundException()
     64
     65        self._keys = list(_keys)
     66        self._path = _path
     67
     68    def read(self, limit: int = 5):
     69        """Reads a JSON file and returns limit number of values from \
     70            corresponding keys.
     71
     72        If one of the corresponding keys doesn't exist, the log warns
     73        that key doesn't exist.
     74        If PermissionError is raised, then the program halts with exit
     75        status 1 and immediately states that permission is denied.
     76
     77        Args:
     78            limit (int, optional): Limit to number of values. Defaults to 5.
     79
     80        Returns:
     81            List[Any] : Values for corresponding keys, i.e, information that
     82            was to searched for.
     83        """
     84        try:
     85            with open(self._path, "r", encoding="utf-8") as file:
     86                data = jsonload(file)
     87                logging.info("JSON loaded successfully from file")
     88
     89                searched_info = []
     90
     91                for key in self._keys:
     92                    if key not in data.keys():
     93                        logging.warning(colored(f"Warning: Key {key} doesn't exist"))
     94                    else:
     95                        for value in data[key]:
     96                            if len(searched_info) >= limit:
     97                                logging.info(
     98                                    "Package is searched and found some entries"
     99                                )
    100                                return searched_info
    101
    102                            searched_info.append(value)
    103
    104                logging.info("Package is searched but no entries found")
    105
    106        except PermissionError:
    107            print(
    108                colored(
    109                    "Error: Permission denied. Please check temp directory permissions.",
    110                    "red",
    111                )
    112            )
    113            sys.exit(1)
    114
    115        return searched_info
    116
    117    def relative_time(self):
    118        """Returns the time difference between last modified time of given file and \
    119            current os time in seconds."""
    120        logging.debug("Relative time is determined")
    121        return time() - os.path.getmtime(self._path)

class FileNotFoundException(builtins.Exception): View Source

    26class FileNotFoundException(Exception):
    27    """Returns FileNotFoundException if file doesn't exist.
    28
    29    This exception is created for manually raising exceptions
    30    if file doesn't exist or given path is not a file path.
    31    These exceptions are handled manually as group.
    32    """

Returns FileNotFoundException if file doesn't exist.

This exception is created for manually raising exceptions if file doesn't exist or given path is not a file path. These exceptions are handled manually as group.

##### Inherited Members

builtins.Exception
  Exception
builtins.BaseException
  with_traceback
  add_note

class JSONFileReader: View Source

     35class JSONFileReader:
     36    """A Custom JSON File Reader class created using requests package.
     37
     38    The class is initialized by a JSON file path (which can be a Path object
     39    or str) and a list of keys to be searched for.
     40
     41    Raises:
     42        FileNotFoundException: Manual Exception class that is raised if \
     43            file doesn't exist or given path is not a file path.
     44    """
     45
     46    _keys: list = []
     47    _path: Union[Path, str] = Path()
     48
     49    def __init__(self, _path: Union[Path, str], *_keys):
     50        if len(_keys) < 1:
     51            print(colored("Error: At least one key is required"))
     52            sys.exit(1)
     53
     54        if not isinstance(_path, Path):
     55            _path = Path(os.path.join(gettempdir(), _path))
     56            logging.info("Path created")
     57
     58            logging.debug("Path created using filename")
     59
     60        else:
     61            logging.debug("Path was directly given")
     62
     63        if not (_path.exists() and _path.is_file()):
     64            raise FileNotFoundException()
     65
     66        self._keys = list(_keys)
     67        self._path = _path
     68
     69    def read(self, limit: int = 5):
     70        """Reads a JSON file and returns limit number of values from \
     71            corresponding keys.
     72
     73        If one of the corresponding keys doesn't exist, the log warns
     74        that key doesn't exist.
     75        If PermissionError is raised, then the program halts with exit
     76        status 1 and immediately states that permission is denied.
     77
     78        Args:
     79            limit (int, optional): Limit to number of values. Defaults to 5.
     80
     81        Returns:
     82            List[Any] : Values for corresponding keys, i.e, information that
     83            was to searched for.
     84        """
     85        try:
     86            with open(self._path, "r", encoding="utf-8") as file:
     87                data = jsonload(file)
     88                logging.info("JSON loaded successfully from file")
     89
     90                searched_info = []
     91
     92                for key in self._keys:
     93                    if key not in data.keys():
     94                        logging.warning(colored(f"Warning: Key {key} doesn't exist"))
     95                    else:
     96                        for value in data[key]:
     97                            if len(searched_info) >= limit:
     98                                logging.info(
     99                                    "Package is searched and found some entries"
    100                                )
    101                                return searched_info
    102
    103                            searched_info.append(value)
    104
    105                logging.info("Package is searched but no entries found")
    106
    107        except PermissionError:
    108            print(
    109                colored(
    110                    "Error: Permission denied. Please check temp directory permissions.",
    111                    "red",
    112                )
    113            )
    114            sys.exit(1)
    115
    116        return searched_info
    117
    118    def relative_time(self):
    119        """Returns the time difference between last modified time of given file and \
    120            current os time in seconds."""
    121        logging.debug("Relative time is determined")
    122        return time() - os.path.getmtime(self._path)

A Custom JSON File Reader class created using requests package.

The class is initialized by a JSON file path (which can be a Path object or str) and a list of keys to be searched for.

###### Raises:

- FileNotFoundException: Manual Exception class that is raised if file doesn't exist or given path is not a file path.

JSONFileReader(_path: Union[pathlib.Path, str], *_keys) View Source

    49    def __init__(self, _path: Union[Path, str], *_keys):
    50        if len(_keys) < 1:
    51            print(colored("Error: At least one key is required"))
    52            sys.exit(1)
    53
    54        if not isinstance(_path, Path):
    55            _path = Path(os.path.join(gettempdir(), _path))
    56            logging.info("Path created")
    57
    58            logging.debug("Path created using filename")
    59
    60        else:
    61            logging.debug("Path was directly given")
    62
    63        if not (_path.exists() and _path.is_file()):
    64            raise FileNotFoundException()
    65
    66        self._keys = list(_keys)
    67        self._path = _path

def read(self, limit: int = 5): View Source

     69    def read(self, limit: int = 5):
     70        """Reads a JSON file and returns limit number of values from \
     71            corresponding keys.
     72
     73        If one of the corresponding keys doesn't exist, the log warns
     74        that key doesn't exist.
     75        If PermissionError is raised, then the program halts with exit
     76        status 1 and immediately states that permission is denied.
     77
     78        Args:
     79            limit (int, optional): Limit to number of values. Defaults to 5.
     80
     81        Returns:
     82            List[Any] : Values for corresponding keys, i.e, information that
     83            was to searched for.
     84        """
     85        try:
     86            with open(self._path, "r", encoding="utf-8") as file:
     87                data = jsonload(file)
     88                logging.info("JSON loaded successfully from file")
     89
     90                searched_info = []
     91
     92                for key in self._keys:
     93                    if key not in data.keys():
     94                        logging.warning(colored(f"Warning: Key {key} doesn't exist"))
     95                    else:
     96                        for value in data[key]:
     97                            if len(searched_info) >= limit:
     98                                logging.info(
     99                                    "Package is searched and found some entries"
    100                                )
    101                                return searched_info
    102
    103                            searched_info.append(value)
    104
    105                logging.info("Package is searched but no entries found")
    106
    107        except PermissionError:
    108            print(
    109                colored(
    110                    "Error: Permission denied. Please check temp directory permissions.",
    111                    "red",
    112                )
    113            )
    114            sys.exit(1)
    115
    116        return searched_info

Reads a JSON file and returns limit number of values from corresponding keys.

If one of the corresponding keys doesn't exist, the log warns that key doesn't exist. If PermissionError is raised, then the program halts with exit status 1 and immediately states that permission is denied.

###### Arguments:

- limit (int, optional): Limit to number of values. Defaults to 5.

###### Returns:

> List[Any] : Values for corresponding keys, i.e, information that was to searched for.

def relative_time(self): View Source

    118    def relative_time(self):
    119        """Returns the time difference between last modified time of given file and \
    120            current os time in seconds."""
    121        logging.debug("Relative time is determined")
    122        return time() - os.path.getmtime(self._path)

Returns the time difference between last modified time of given file and current os time in seconds.