Source code for fhirpack.config
import sys
from pathlib import Path
import traceback
import logging
import dotenv
from fhirpack.exceptions import ConfigurationFileNotFound
[docs]class Config:
"""Used to manage the configuration of the package."""
__CONFIG = dict()
__DOTENVPATH = None
def __init__(self):
if len(self.__CONFIG) == 0:
self.loadConfig()
self.__configLogger(self)
[docs] def loadConfig(self, dotenvPath: str = None):
"""Loads a FHIRPACK configuration from the given .env file.
Args:
dotenvPath (Union[str, None]): Path to the .env file. Defaults to None.
"""
# try to find a suitable .env file if none is provided
if not dotenvPath:
dotenvPath = dotenv.find_dotenv()
# TODO: decide whether to fail or attempt rescue via .env.example
dotenvPath = ".env.example" if not dotenvPath else dotenvPath
else:
dotenvPath = Path(dotenvPath)
if not dotenvPath.is_file():
raise ConfigurationFileNotFound
config = dotenv.dotenv_values(dotenvPath)
self.__CONFIG = config
self.__DOTENVPATH = dotenvPath
[docs] def globalExceptionHandler(self, exctype, value, tb):
logger = logging.getLogger(__name__)
logger.error(exctype)
logger.error(value)
logger.error(traceback.extract_tb(tb))
@property
def data(self):
return self.__CONFIG
@data.setter
def data(self, data):
self.__CONFIG = data
@staticmethod
def __configLogger(self):
"""Configures the logger to be used throughout FHIRPACK."""
logging.basicConfig(
filename=f"./fhirpack.log",
filemode="a+",
format="%(asctime)s, %(msecs)d %(name)s %(levelname)s [ %(filename)s-%(lineno)d-%(funcName)20s() ] : %(message)s",
# format="%(message)s",
datefmt="%H:%M:%S",
level=logging.INFO,
)
sys.excepthook = Config.globalExceptionHandler
[docs] def set(self, key: str, value: str, saveToEnv: bool = False):
"""Set a configuration variable.
Args:
key (str): Key of the configuration variable.
value (str): Value of the configuration variable.
saveToEnv (Union[bool, None]): Whether to save the configuration variable to the .env file. Defaults to False.
Returns:
str: Value of the configuration variable.
"""
if saveToEnv:
dotenv.set_key(self.__DOTENVPATH, key, value)
return self.__CONFIG.update({key: value})
[docs] def get(self, key):
return self.__CONFIG.get(key)
[docs] def getLogger(self, name: str):
"""Returns a logger instance.
Args:
name (str): Name of the logger.
Returns:
logging.Logger: Logger.
"""
return logging.getLogger(name)
# TODO create @properties for all compulsory configuration varibles in .env
# def __customize(self):
# self.set(
# 'AUTH_PARAMS_PRESETS_SHIP',
# {
# 'preprocessTokenEndpointResponse':True,
# 'tokenEndpointResponsePreprocessor': Auth.parseSHIPTokenEndpointResponse,
# 'headers':{'Accept':'*/*'}
# }
# )