def getSetting(self, nodeKey, settingTree=None): if not settingTree: settingTree = self.settingTree settingValue = SettingHelper.getSetting(nodeKey, settingTree) if ObjectHelper.isEmpty(settingValue): return SettingHelper.getSetting(nodeKey, self.defaultSettingTree) return settingValue
def mustLogEnvironmentSettings(): # Arrange # Act SettingHelper.logEnvironmentSettings() # Assert assert SettingHelper.LOCAL_ENVIRONMENT == EnvironmentHelper.get( SettingHelper.ACTIVE_ENVIRONMENT) assert SettingHelper.LOCAL_ENVIRONMENT == SettingHelper.getActiveEnvironment( ) assert SettingHelper.activeEnvironmentIsLocal() assert "some value" == EnvironmentHelper.get('SOME_PARTICULAR_SETTING')
def getJwtMannager(appInstance, jwtSecret, algorithm=None, headerName=None, headerType=None): if not jwtSecret: log.warning( getJwtMannager, f'Not possible to instanciate sessionManager{c.DOT_SPACE_CAUSE}Missing jwt secret at {ConfigurationKeyConstant.API_SESSION_SECRET}' ) else: jwtManager = JwtManager( jwtSecret, ConverterStatic.getValueOrDefault( algorithm, JwtConstant.DEFAULT_JWT_SESSION_ALGORITHM), ConverterStatic.getValueOrDefault( headerName, JwtConstant.DEFAULT_JWT_SESSION_HEADER_NAME), ConverterStatic.getValueOrDefault( headerType, JwtConstant.DEFAULT_JWT_SESSION_HEADER_TYPE)) if SettingHelper.activeEnvironmentIsLocal(): info = { 'secret': jwtManager.secret, 'algorithm': jwtManager.algorithm, 'headerName': jwtManager.headerName, 'headerType': jwtManager.headerType } log.prettyJson(getJwtMannager, f'JWT session', info, logLevel=log.SETTING) return jwtManager
def getSettingTree(self, settingFilePath=None, defaultSettingFilePath=None, settingTree=None): if ObjectHelper.isEmpty(settingTree): settingTree = {} fallbackSettingFilePath = defaultSettingFilePath if not settingFilePath == defaultSettingFilePath else None if ObjectHelper.isNone(settingFilePath) or StringHelper.isBlank( settingFilePath ) or not EnvironmentHelper.OS.path.isfile(settingFilePath): self.failure( f'The "{settingFilePath}" setting file path was not found', None) return self.getSettingTree(settingFilePath=fallbackSettingFilePath, settingTree=settingTree) try: settingTree = SettingHelper.getSettingTree( settingFilePath, fallbackSettingFilePath=fallbackSettingFilePath, fallbackSettingTree=settingTree, keepDepthInLongString=True) except Exception as exception: if ObjectHelper.isNone(fallbackSettingFilePath): self.error( f'Failed to load setting tree from "{settingFilePath}" setting file path. Returning {settingTree} by default', exception) else: self.failure( f'Failed to load setting tree from "{settingFilePath}" setting file path and "{fallbackSettingFilePath}" default setting file path. Only setting file path will be loadded now', exception) try: settingTree = SettingHelper.getSettingTree( settingFilePath, keepDepthInLongString=True) except Exception as exception: self.failure( f'Failed to load setting tree from "{settingFilePath}" setting file path as well. Returning {settingTree} by default', exception) return settingTree
def loadLocalConfiguration(self, loadLocalConfig, printRootPathStatus, globalsEverything): self.loadLocalConfig = loadLocalConfig self.localConfiguration = {} if self.loadLocalConfig: try: self.localConfiguration = self.getSettingTree( settingFilePath=Globals.LOCAL_CONFIGURATION_FILE_NAME, settingTree=None) except Exception as exception: self.log( f'Failed to load {Globals.LOCAL_CONFIGURATION_FILE_NAME} settings', exception=exception) keyQuery = SettingHelper.querySetting(AttributeKey.KW_KEY, self.localConfiguration) keyValueQuery = {} for key, value in keyQuery.items(): KW_DOT_KEY = f'{c.DOT}{AttributeKey.KW_KEY}' if key.endswith(KW_DOT_KEY): environmentInjection = SettingHelper.getSetting( key[:-len(KW_DOT_KEY)], self.localConfiguration) if (ObjectHelper.isDictionary(environmentInjection) and AttributeKey.KW_KEY in environmentInjection and AttributeKey.KW_VALUE in environmentInjection and 2 == len(environmentInjection)): EnvironmentHelper.update( environmentInjection[AttributeKey.KW_KEY], environmentInjection[AttributeKey.KW_VALUE]) log.loadSettings() self.printRootPathStatus = printRootPathStatus self.globalsEverything = globalsEverything self.ignoreModules = IGNORE_MODULES self.ignoreResources = IGNORE_REOURCES self.activeEnvironment = SettingHelper.getActiveEnvironment() if ObjectHelper.isNotEmpty( self.localConfiguration) and SettingHelper.getSetting( 'print-status', self.localConfiguration): SettingHelper.printSettings(self.localConfiguration, "Local Configuration") basicSettingsAsDictionary = { 'activeEnvironment': self.activeEnvironment, 'successStatus': self.successStatus, 'settingStatus': self.settingStatus, 'debugStatus': self.debugStatus, 'warningStatus': self.warningStatus, 'failureStatus': self.failureStatus, 'errorStatus': self.errorStatus, 'wrapperStatus': self.wrapperStatus, 'infoStatus': self.infoStatus, 'statusStatus': self.statusStatus, 'logStatus': self.logStatus, 'globalsEverything': self.globalsEverything, 'printRootPathStatus': self.printRootPathStatus } log.prettyPython(self.__class__, f'Basic settings', basicSettingsAsDictionary, logLevel=log.SETTING)
def shouldHandleMissingEnvironmentSettings(): # Arrange exception = None globalsInstance = None # Act try: globalsInstance = globals.newGlobalsInstance(__file__, loadLocalConfig=False) except Exception as ext: exception = ext # Assert assert ObjectHelper.isNotNone(globalsInstance) assert ObjectHelper.isNone(exception) assert 'missing_setting_file' == EnvironmentHelper.get( SettingHelper.ACTIVE_ENVIRONMENT) assert 'missing_setting_file' == SettingHelper.getActiveEnvironment()
def initialize( rootName, refferenceModel, ): app = Flask(rootName) api = Api(app) addGlobalsTo(api) SchedulerManager.addScheduler(api, app) securityKey = api.globals.getApiSetting('api.security.secret') if SettingHelper.LOCAL_ENVIRONMENT == SettingHelper.getActiveEnvironment(): log.setting(initialize, f'JWT secret: {securityKey}') jwt = Security.getJwtMannager(app, securityKey) args = [api, app, jwt] for resourceType in FlaskManager.KW_RESOURCE_LIST: args.append(getResourceList(api, resourceType)) args.append(refferenceModel) addFlaskApiResources(*args) api.app = app return api, app, jwt
def getJwtMannager(appInstance, jwtSecret, algorithm=None, headerName=None, headerType=None): if ObjectHelper.isNone(jwtSecret): log.warning( getJwtMannager, f'Not possible to instanciate securityManager{c.DOT_SPACE_CAUSE}Missing jwt secret at {ConfigurationKeyConstant.API_SECURITY_SECRET}' ) else: jwtMannager = JWTManager(appInstance) appInstance.config[JwtConstant.KW_JWT_SECRET_KEY] = jwtSecret appInstance.config[JwtConstant.KW_JWT_BLACKLIST_ENABLED] = True appInstance.config[ JwtConstant.KW_JWT_ALGORITHM] = ConverterStatic.getValueOrDefault( algorithm, JwtConstant.DEFAULT_JWT_SECURITY_ALGORITHM) appInstance.config[ JwtConstant. KW_JWT_HEADER_NAME] = ConverterStatic.getValueOrDefault( headerName, JwtConstant.DEFAULT_JWT_SECURITY_HEADER_NAME) appInstance.config[ JwtConstant. KW_JWT_HEADER_TYPE] = ConverterStatic.getValueOrDefault( headerType, JwtConstant.DEFAULT_JWT_SECURITY_HEADER_TYPE) if SettingHelper.activeEnvironmentIsLocal(): info = { 'secret': jwtSecret, 'algorithm': appInstance.config[JwtConstant.KW_JWT_ALGORITHM], 'headerName': appInstance.config[JwtConstant.KW_JWT_HEADER_NAME], 'headerType': appInstance.config[JwtConstant.KW_JWT_HEADER_TYPE] } log.prettyJson(getJwtMannager, f'JWT security', info, logLevel=log.SETTING) return jwtMannager
def printTree(self, tree, name, depth=1): SettingHelper.printSettings(tree, name, depth=depth)
def accessTree(self, nodeKey, tree): return SettingHelper.getSetting(nodeKey, tree)
def getActiveEnvironment(self): return SettingHelper.getActiveEnvironment()
def mustLogWithColors(): # Arrange noExceptionThrown = 'exception not thrown' someLogMessage = 'some log message' someExceptionMessage = 'some exception message' someInnerExceptionMessage = 'some inner exception message' exception = None someExceptionMessageWithStackTrace = f'{someExceptionMessage} with stacktrace' someExceptionMessageWithoutStackTrace = f'{someExceptionMessage} without stacktrace' def controlableException(logType, muteStackTrace=False): try: raise Exception( someExceptionMessageWithoutStackTrace if muteStackTrace else someExceptionMessageWithStackTrace) except Exception as exception: if logType in OPTIONAL_EXCEPTION_LOG_TYPES: logType(logType, someLogMessage, exception=exception, muteStackTrace=muteStackTrace) else: logType(logType, someLogMessage, exception, muteStackTrace=muteStackTrace) # Act log.success(log.success, someLogMessage) log.setting(log.setting, someLogMessage) log.debug(log.debug, someLogMessage) log.warning(log.warning, someLogMessage) controlableException(log.log) controlableException(log.debug) controlableException(log.warning) controlableException(log.wraper) controlableException(log.failure) controlableException(log.error) controlableException(log.test) controlableException(log.log, muteStackTrace=True) controlableException(log.debug, muteStackTrace=True) controlableException(log.warning, muteStackTrace=True) controlableException(log.wraper, muteStackTrace=True) controlableException(log.failure, muteStackTrace=True) controlableException(log.error, muteStackTrace=True) controlableException(log.test, muteStackTrace=True) log.log(log.log, someLogMessage, None) log.debug(log.debug, someLogMessage, None) log.warning(log.warning, someLogMessage, None) log.wraper(log.wraper, noExceptionThrown, None) log.failure(log.failure, noExceptionThrown, None) log.error(log.error, noExceptionThrown, None) log.test(log.test, someLogMessage, None) # Assert assert SettingHelper.LOCAL_ENVIRONMENT == EnvironmentHelper.get( SettingHelper.ACTIVE_ENVIRONMENT) assert SettingHelper.activeEnvironmentIsLocal()
def mustPrintMessageLog_withColors(): # Arrange mustLogWithNewLine = 'must log with new line' mustNotLogWithNewLine = 'must not log with new line' mustLogWithoutNewLine = 'must log without new line' mustNotLogWithoutNewLine = 'must not log without new line' mustLogWithNewLineWithException = 'must log with new line with exception' mustNotLogWithNewLineWithException = 'must not log with new line with exception' mustLogWithoutNewLineWithException = 'must log without new line with exception' mustNotLogWithoutNewLineWithException = 'must not log without new line with exception' someExceptionMessage = 'some exception message' thrownException = None try: raise Exception(someExceptionMessage) except Exception as exception: thrownException = exception # Act log.printLog(mustLogWithNewLine, condition=True, newLine=True) log.printSuccess(mustLogWithNewLine, condition=True, newLine=True) log.printSetting(mustLogWithNewLine, condition=True, newLine=True) log.printDebug(mustLogWithNewLine, condition=True, newLine=True, exception=None) log.printWarning(mustLogWithNewLine, condition=True, newLine=True, exception=None) log.printWarper(mustLogWithNewLine, condition=True, newLine=True, exception=None) log.printFailure(mustLogWithNewLine, condition=True, newLine=True, exception=None) log.printError(mustLogWithNewLine, condition=True, newLine=True, exception=None) log.printTest(mustLogWithNewLine, condition=True, newLine=True, exception=None) log.printLog(mustNotLogWithNewLine, condition=False, newLine=True) log.printSuccess(mustNotLogWithNewLine, condition=False, newLine=True) log.printSetting(mustNotLogWithNewLine, condition=False, newLine=True) log.printDebug(mustNotLogWithNewLine, condition=False, newLine=True, exception=None) log.printWarning(mustNotLogWithNewLine, condition=False, newLine=True, exception=None) log.printWarper(mustNotLogWithNewLine, condition=False, newLine=True, exception=None) log.printFailure(mustNotLogWithNewLine, condition=False, newLine=True, exception=None) log.printError(mustNotLogWithNewLine, condition=False, newLine=True, exception=None) log.printTest(mustNotLogWithNewLine, condition=False, newLine=True, exception=None) log.printLog(mustLogWithoutNewLine, condition=True, newLine=False) log.printSuccess(mustLogWithoutNewLine, condition=True, newLine=False) log.printSetting(mustLogWithoutNewLine, condition=True, newLine=False) log.printDebug(mustLogWithoutNewLine, condition=True, newLine=False, exception=None) log.printWarning(mustLogWithoutNewLine, condition=True, newLine=False, exception=None) log.printWarper(mustLogWithoutNewLine, condition=True, newLine=False, exception=None) log.printFailure(mustLogWithoutNewLine, condition=True, newLine=False, exception=None) log.printError(mustLogWithoutNewLine, condition=True, newLine=False, exception=None) log.printTest(mustLogWithoutNewLine, condition=True, newLine=False, exception=None) log.printLog(mustNotLogWithoutNewLine, condition=False, newLine=False) log.printSuccess(mustNotLogWithoutNewLine, condition=False, newLine=False) log.printSetting(mustNotLogWithoutNewLine, condition=False, newLine=False) log.printDebug(mustNotLogWithoutNewLine, condition=False, newLine=False, exception=None) log.printWarning(mustNotLogWithoutNewLine, condition=False, newLine=False, exception=None) log.printWarper(mustNotLogWithoutNewLine, condition=False, newLine=False, exception=None) log.printFailure(mustNotLogWithoutNewLine, condition=False, newLine=False, exception=None) log.printError(mustNotLogWithoutNewLine, condition=False, newLine=False, exception=None) log.printTest(mustNotLogWithoutNewLine, condition=False, newLine=False, exception=None) log.printLog(mustLogWithNewLineWithException, condition=True, newLine=True, exception=thrownException) log.printDebug(mustLogWithNewLineWithException, condition=True, newLine=True, exception=thrownException) log.printWarning(mustLogWithNewLineWithException, condition=True, newLine=True, exception=thrownException) log.printWarper(mustLogWithNewLineWithException, condition=True, newLine=True, exception=thrownException) log.printFailure(mustLogWithNewLineWithException, condition=True, newLine=True, exception=thrownException) log.printError(mustLogWithNewLineWithException, condition=True, newLine=True, exception=thrownException) log.printTest(mustLogWithNewLineWithException, condition=True, newLine=True, exception=thrownException) log.printLog(mustLogWithoutNewLineWithException, condition=True, newLine=False, exception=thrownException) log.printDebug(mustLogWithoutNewLineWithException, condition=True, newLine=False, exception=thrownException) log.printWarning(mustLogWithoutNewLineWithException, condition=True, newLine=False, exception=thrownException) log.printWarper(mustLogWithoutNewLineWithException, condition=True, newLine=False, exception=thrownException) log.printFailure(mustLogWithoutNewLineWithException, condition=True, newLine=False, exception=thrownException) log.printError(mustLogWithoutNewLineWithException, condition=True, newLine=False, exception=thrownException) log.printTest(mustLogWithoutNewLineWithException, condition=True, newLine=False, exception=thrownException) log.printLog(mustNotLogWithNewLineWithException, condition=False, newLine=True, exception=thrownException) log.printDebug(mustNotLogWithNewLineWithException, condition=False, newLine=True, exception=thrownException) log.printWarning(mustNotLogWithNewLineWithException, condition=False, newLine=True, exception=thrownException) log.printWarper(mustNotLogWithNewLineWithException, condition=False, newLine=True, exception=thrownException) log.printFailure(mustNotLogWithNewLineWithException, condition=False, newLine=True, exception=thrownException) log.printError(mustNotLogWithNewLineWithException, condition=False, newLine=True, exception=thrownException) log.printTest(mustNotLogWithNewLineWithException, condition=False, newLine=True, exception=thrownException) log.printLog(mustNotLogWithoutNewLineWithException, condition=False, newLine=False, exception=thrownException) log.printDebug(mustNotLogWithoutNewLineWithException, condition=False, newLine=False, exception=thrownException) log.printWarning(mustNotLogWithoutNewLineWithException, condition=False, newLine=False, exception=thrownException) log.printWarper(mustNotLogWithoutNewLineWithException, condition=False, newLine=False, exception=thrownException) log.printFailure(mustNotLogWithoutNewLineWithException, condition=False, newLine=False, exception=thrownException) log.printError(mustNotLogWithoutNewLineWithException, condition=False, newLine=False, exception=thrownException) log.printTest(mustNotLogWithoutNewLineWithException, condition=False, newLine=False, exception=thrownException) # Assert assert True == SettingHelper.activeEnvironmentIsLocal() assert SettingHelper.LOCAL_ENVIRONMENT == EnvironmentHelper.get( SettingHelper.ACTIVE_ENVIRONMENT) assert SettingHelper.LOCAL_ENVIRONMENT == SettingHelper.getActiveEnvironment( )
def getUrl(self, dialect): log.log(self.getUrl, 'Loading repository configuration') url = EnvironmentHelper.get(self.ENV_DATABASE_URL) if isNeitherNoneNorBlank(url): dialect = None driver = None database = None username = None password = None host = None port = None schema = None log.log( self.getUrl, f'Prioritising repository url in {self.ENV_DATABASE_URL} environment variable' ) else: url = self.globals.getSetting( f'{self.KW_API}{c.DOT}{self.KW_DATABASE}{c.DOT}{self.KW_REPOSITORY_URL}' ) if isNeitherNoneNorBlank(url): dialect = None driver = None database = None username = None password = None host = None port = None schema = None log.log(self.getUrl, f'Prioritising repository url in yamel configuration') else: url = c.NOTHING driver = self.globals.getSetting( f'{self.KW_API}{c.DOT}{self.KW_DATABASE}{c.DOT}{self.KW_REPOSITORY_DRIVER}' ) database = self.globals.getSetting( f'{self.KW_API}{c.DOT}{self.KW_DATABASE}{c.DOT}{self.KW_REPOSITORY_DATABASE}' ) username = self.globals.getSetting( f'{self.KW_API}{c.DOT}{self.KW_DATABASE}{c.DOT}{self.KW_REPOSITORY_USERNAME}' ) password = self.globals.getSetting( f'{self.KW_API}{c.DOT}{self.KW_DATABASE}{c.DOT}{self.KW_REPOSITORY_PASSWORD}' ) host = self.globals.getSetting( f'{self.KW_API}{c.DOT}{self.KW_DATABASE}{c.DOT}{self.KW_REPOSITORY_HOST}' ) port = self.globals.getSetting( f'{self.KW_API}{c.DOT}{self.KW_DATABASE}{c.DOT}{self.KW_REPOSITORY_PORT}' ) schema = self.globals.getSetting( f'{self.KW_API}{c.DOT}{self.KW_DATABASE}{c.DOT}{self.KW_REPOSITORY_SCHEMA}' ) if isNeitherNoneNorBlank(username) and isNeitherNoneNorBlank( password): url += f'{username}{c.COLON}{password}' if isNeitherNoneNorBlank(host) and isNeitherNoneNorBlank(port): url += f'{c.ARROBA}{host}{c.COLON}{port}' url += c.SLASH database = f'{database}' if isNeitherNoneNorBlank( database ) else f'{self.DEFAULT_LOCAL_STORAGE_NAME if ObjectHelper.isNone(self.globals.apiName) else self.globals.apiName}{c.DOT}{self.EXTENSION}' if not isNeitherNoneNorBlank(dialect): dialect = self.DEFAULT_DIALECT plusDriverOrNothing = f'{c.PLUS}{driver}' if isNeitherNoneNorBlank( driver) else c.NOTHING dialectAndDriver = f'''{dialect}{plusDriverOrNothing}''' url = f'{dialectAndDriver}{c.COLON}{c.DOUBLE_SLASH}{url}{database}' log.log(self.getUrl, 'Prioritising repository yamel configuration') if SettingHelper.activeEnvironmentIsLocal(): log.prettyJson( self.getUrl, 'Repository configuations', { **self.globals.getSetting(f'{self.KW_API}{c.DOT}{self.KW_DATABASE}'), **{ 'dialect': dialect, 'driver': driver, 'database': database, 'username': username, 'password': password, 'host': host, 'port': port, 'schema': schema, 'url': url } }, logLevel=log.SETTING) # log.prettyPython(self.getUrl, 'url', url, logLevel=log.LOG) return url
from python_helper import EnvironmentHelper, log from python_helper import SettingHelper import globals globalsInstance = globals.newGlobalsInstance(__file__ , loadLocalConfig = SettingHelper.activeEnvironmentIsDefault() , settingStatus = True , successStatus = True , errorStatus = True , debugStatus = True , failureStatus = True , warningStatus = True , wrapperStatus = True , logStatus = True # , testStatus = True ) from python_framework.api.src.service.flask import FlaskManager import TestApi app = TestApi.app api = TestApi.api jwt = TestApi.jwt @FlaskManager.initialize(api, defaultUrl = '/swagger', openInBrowser=False) def runFlaskApplication(app=None): FlaskManager.runApi(debug=False, use_reloader=False) # app.run(debug=False, use_reloader=False) # app.run(debug=True)