def Enum_dot_map(): # arrange @Enum(instanceLog=False) class SimpleEnum: ABC = EnumItem() DEF = EnumItem() SIMPLE_ENUM = SimpleEnum() @Enum(instanceLog=False) class MyEnumTest: ONE = EnumItem(value='one', otherValue=1) TWO = EnumItem(value='two', otherValue=2) MY_ENUM_TEST = MyEnumTest() @Enum(associateReturnsTo='otherValue', instanceLog=False) class MyThirdEnumTest: THREE = EnumItem(value='three', otherValue=3) FOUR = EnumItem(value='four', otherValue=4) MY_THIRD_ENUM_TEST = MyThirdEnumTest() # act shouldBe_DEF = SIMPLE_ENUM.map('DEF') shouldBe_DEF_asWell = SIMPLE_ENUM.map(SIMPLE_ENUM.map('DEF')) shouldBe_None = SIMPLE_ENUM.map(None) # assert assert shouldBe_None is None assert shouldBe_DEF == SIMPLE_ENUM.DEF assert shouldBe_DEF is not {} assert not SIMPLE_ENUM.map('DEF') == SIMPLE_ENUM.map('ABC') assert not MY_ENUM_TEST.map('ONE') == MY_ENUM_TEST.map('TWO') assert shouldBe_DEF_asWell == SIMPLE_ENUM.DEF assert shouldBe_DEF_asWell is not {} assert ObjectHelper.isNotEmpty(shouldBe_DEF_asWell) assert MY_ENUM_TEST.map('ONE') == MY_ENUM_TEST.ONE assert not MY_ENUM_TEST.map('ONE') == MY_ENUM_TEST.TWO assert MY_ENUM_TEST.map('ONE') is not {} assert ObjectHelper.isNotEmpty(MY_ENUM_TEST.map('TWO')) assert MY_THIRD_ENUM_TEST.map(3) == MY_THIRD_ENUM_TEST.THREE assert not MY_THIRD_ENUM_TEST.map(4) == MY_THIRD_ENUM_TEST.THREE assert MY_THIRD_ENUM_TEST.map(4) is not {} assert ObjectHelper.isNotEmpty(MY_THIRD_ENUM_TEST.map(3)) assert MY_THIRD_ENUM_TEST.map('THREE') == MY_THIRD_ENUM_TEST.THREE assert not MY_THIRD_ENUM_TEST.map('FOUR') == MY_THIRD_ENUM_TEST.THREE assert MY_THIRD_ENUM_TEST.map('FOUR') is not {} assert ObjectHelper.isNotEmpty(MY_THIRD_ENUM_TEST.map('THREE'))
def validateKwargs(kwargs, resourceInstance, resourceInstanceMethod, requestHeaderClass, requestParamClass): classListToValidate = [] instanceListToValidate = [] if ObjectHelper.isNotEmpty(requestHeaderClass): classListToValidate.append( requestHeaderClass if ObjectHelper. isNotList(requestHeaderClass) else requestHeaderClass[0]) instanceListToValidate.append(kwargs.get(FlaskUtil.KW_HEADERS, {})) if ObjectHelper.isNotEmpty(requestParamClass): classListToValidate.append(requestParamClass if ObjectHelper.isNotList( requestParamClass) else requestParamClass[0]) instanceListToValidate.append(kwargs.get(FlaskUtil.KW_PARAMETERS, {})) validateArgs([resourceInstance, *instanceListToValidate], classListToValidate, resourceInstanceMethod)
def addControllerListTo(apiInstance, controllerList): for controller in controllerList: OpenApiManager.addControllerDocumentation(controller, apiInstance) mainUrl = f'{apiInstance.baseUrl}{controller.url}' urlList = [mainUrl] infoList = [f'Controller: {mainUrl}'] controllerMethodList = ReflectionHelper.getAttributePointerList( controller) for controllerMethod in controllerMethodList: if ReflectionHelper.hasAttributeOrMethod( controllerMethod, FlaskManager.KW_URL) and ObjectHelper.isNotEmpty( controllerMethod.url): controllerUrl = f'{mainUrl}{controllerMethod.url}' if controllerUrl not in urlList: urlList.append(controllerUrl) infoList.append( f'{c.TAB}{ReflectionHelper.getName(controllerMethod)}: {controllerUrl}' ) # subUrlList = controllerMethod.url.split(c.SLASH) # concatenatedSubUrl = c.NOTHING # for subUrl in subUrlList : # if subUrl : # concatenatedSubUrl += f'{c.SLASH}{subUrl}' # if c.LESSER == subUrl[0] and c.BIGGER == subUrl[-1] : # newUrl = f'{apiInstance.baseUrl}{controller.url}{concatenatedSubUrl}' # if not newUrl in urlList : # urlList.append(newUrl) OpenApiManager.addEndPointDocumentation( controllerUrl, controllerMethod, controller, apiInstance) log.debug( addControllerListTo, f'{controller.url} -> {StringHelper.prettyPython(infoList)}') apiInstance.add_resource(controller, *urlList)
def addToKwargs(key, givenClass, valuesAsDictionary, kwargs): if ObjectHelper.isNotEmpty(givenClass): toClass = givenClass if ObjectHelper.isNotList( givenClass) else givenClass[0] kwargs[key] = Serializer.convertFromJsonToObject( {k: v for k, v in valuesAsDictionary.items()}, toClass)
def validateGeneralSessionAndReturnItDecoded(self, rawJwt=None, options=None): decodedSessionToken = rawJwt try: decodedSessionToken = self.getDecodedToken( rawJwt=decodedSessionToken, options=options) assert ObjectHelper.isDictionary( decodedSessionToken ), f'Invalid session payload type. It should be a dictionary, bu it is {type(decodedSessionToken)}' assert ObjectHelper.isNotEmpty( decodedSessionToken), 'Session cannot be empty' jti = getJti(rawJwt=decodedSessionToken) assert ObjectHelper.isNotNone(jti), f'JWT jti cannot be None' assert jti not in BLACK_LIST, f'Session {jti} already revoked' nbf = getNfb(rawJwt=decodedSessionToken) assert ObjectHelper.isNotNone(nbf), f'JWT nbf cannot be None' assert UtcDateTimeUtil.now() >= UtcDateTimeUtil.ofTimestamp( nbf ), f'JWT session token not valid before {UtcDateTimeUtil.ofTimestamp(nbf)}' expiration = getExpiration(rawJwt=decodedSessionToken) assert UtcDateTimeUtil.now() <= UtcDateTimeUtil.ofTimestamp( expiration ), f'JWT session token expired at {UtcDateTimeUtil.ofTimestamp(expiration)}' except Exception as exception: addAccessTokenToBlackList(rawJwt=decodedSessionToken) log.log(self.validateGeneralSessionAndReturnItDecoded, f'Adding {rawJwt} (or current accces) to blackList', exception=exception, muteStackTrace=True) raise exception return decodedSessionToken
def __init__(self, message=None, logMessage=None, status=None, logResource=None, logResourceMethod=None, verb=None, url=None, logPayload=None, logHeaders=None, context=None): self.timeStamp = DateTimeHelper.now() self.status = HttpStatus.map(DEFAULT_STATUS if ObjectHelper. isNone(status) else status).enumValue self.message = message if ObjectHelper.isNotEmpty( message ) and StringHelper.isNotBlank( message ) else DEFAULT_MESSAGE if 500 <= self.status else self.status.enumName self.verb = verb if ObjectHelper.isNotNone( verb) else self.getRequestVerb() self.url = url if ObjectHelper.isNotNone(url) else self.getRequestUrl() self.logMessage = DEFAULT_LOG_MESSAGE if ObjectHelper.isNone( logMessage) or StringHelper.isBlank(logMessage) else logMessage self.logResource = DEFAULT_LOG_RESOURCE if ObjectHelper.isNone( logResource) else logResource self.logResourceMethod = DEFAULT_LOG_RESOURCE_METHOD if ObjectHelper.isNone( logResourceMethod) else logResourceMethod self.logPayload = logPayload if ObjectHelper.isNotNone( logPayload) else self.getRequestBody() self.logHeaders = logHeaders if ObjectHelper.isNotNone( logHeaders) else self.getRequestHeaders() self.context = HttpDomain.CONTROLLER_CONTEXT if ObjectHelper.isNone( context) else context
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 handleEnvironmentChangesProperly_withError(): beforeTestEnvironmentSettings = {**EnvironmentHelper.getSet()} inBetweenTestEnvironmentSettings = None afterTestEnvironmentSettings = None someExceptionMessage = 'some exception message' # Arrange def myBeforeAction(c, d=None): return d + c def myAfterAction(c, d=None): return c + d def myFunction(a): raise Exception(someExceptionMessage) returns = {} @Test(callBefore=myBeforeAction, argsOfCallBefore='f', kwargsOfCallBefore={'d': 'g'}, callAfter=myAfterAction, argsOfCallAfter='h', kwargsOfCallAfter={'d': 'i'}, returns=returns, environmentVariables={ SettingHelper.ACTIVE_ENVIRONMENT: None, **MUTED_LOG_HELPER_SETTINGS }) def myTest(): inBetweenTestEnvironmentSettings = EnvironmentHelper.getSet() assert ObjectHelper.isNotNone(inBetweenTestEnvironmentSettings) assert ObjectHelper.isDictionary(inBetweenTestEnvironmentSettings) assert 'a' == myFunction('a') return inBetweenTestEnvironmentSettings # Act try: inBetweenTestEnvironmentSettings = myTest() except Exception as e: exception = e afterTestEnvironmentSettings = {**EnvironmentHelper.getSet()} # Assert assert 'gf' == returns['returnOfCallBefore'] assert 'hi' == returns['returnOfCallAfter'] assert ObjectHelper.isNotEmpty(exception) assert someExceptionMessage == str(exception) assert ObjectHelper.isNotNone(beforeTestEnvironmentSettings) assert ObjectHelper.isDictionary(beforeTestEnvironmentSettings) assert ObjectHelper.isNone(inBetweenTestEnvironmentSettings) assert ObjectHelper.isNotNone(afterTestEnvironmentSettings) assert ObjectHelper.isDictionary(afterTestEnvironmentSettings) assert afterTestEnvironmentSettings == beforeTestEnvironmentSettings assert not beforeTestEnvironmentSettings == inBetweenTestEnvironmentSettings
def buildApplicationPath(self): if ObjectHelper.isNotEmpty(self.filePath): self.currentPath = f'{str(Path(self.filePath).parent.absolute())}{EnvironmentHelper.OS_SEPARATOR}' else: self.currentPath = f'{str(Path(__file__).parent.absolute())}{EnvironmentHelper.OS_SEPARATOR}' self.log(f'{self.__class__.__name__}{c.DOT}filePath: {self.filePath}') self.log( f'{self.__class__.__name__}{c.DOT}currentPath: {self.currentPath}') self.localPath = str(Path.home()) if not self.localPath[-1] == str(EnvironmentHelper.OS_SEPARATOR): self.localPath = f'{self.localPath}{EnvironmentHelper.OS_SEPARATOR}' self.log( f'{self.__class__.__name__}{c.DOT}localPath: {self.localPath}') self.baseApiPath = Globals.BASE_API_PATH self.apiPath = self.currentPath.split(self.baseApiPath)[0] self.log(f'{self.__class__.__name__}{c.DOT}apiPath: {self.apiPath}') lastLocalPathPackage = self.localPath.split( EnvironmentHelper.OS_SEPARATOR)[-2] firstBaseApiPath = self.baseApiPath.split( EnvironmentHelper.OS_SEPARATOR)[0] lastLocalPathPackageNotFound = True self.apiPackage = c.NOTHING for currentPackage in self.currentPath.split( EnvironmentHelper.OS_SEPARATOR): if lastLocalPathPackageNotFound: if currentPackage == lastLocalPathPackage: lastLocalPathPackageNotFound = False elif not currentPackage or currentPackage == firstBaseApiPath: break else: self.apiPackage = currentPackage self.log( f'{self.__class__.__name__}{c.DOT}apiPackage: {self.apiPackage}') if StringHelper.isNotBlank(self.apiPackage): if len( self.currentPath.split(self.localPath)[1].split( self.apiPackage)) > 1: self.apisRoot = self.currentPath.split( self.localPath)[1].split(self.apiPackage)[0] self.apisPath = f'{self.currentPath.split(self.apiPackage)[0]}' else: self.apisRoot = c.NOTHING self.apisPath = c.NOTHING self.log(f'{self.__class__.__name__}{c.DOT}apisRoot: {self.apisRoot}') self.log(f'{self.__class__.__name__}{c.DOT}apisPath: {self.apisPath}')
def innerMethodWrapper(resourceInstanceMethod, *innerMethodArgs, **innerMethodKwargs): log.debug(SchedulerMethod, f'''wrapping {resourceInstanceMethod.__name__}''') apiInstance = FlaskManager.getApi() methodClassName = ReflectionHelper.getMethodClassName( resourceInstanceMethod) methodName = ReflectionHelper.getName(resourceInstanceMethod) methodKwargs['id'] = methodKwargs.get( 'id', f'{methodClassName}{c.DOT}{methodName}') instancesUpTo = methodKwargs.pop('instancesUpTo', 1) weekDays = methodKwargs.pop('weekDays', None) if ObjectHelper.isNotEmpty( methodArgs ) and SchedulerType.CRON == methodArgs[0] and ObjectHelper.isNotNone( weekDays) and StringHelper.isNotBlank(weekDays): methodKwargs['day_of_week'] = weekDays if ObjectHelper.isNotNone(instancesUpTo): methodKwargs['max_instances'] = instancesUpTo shedulerArgs = [*methodArgs] shedulerKwargs = {**methodKwargs} @apiInstance.scheduler.task(*shedulerArgs, **shedulerKwargs) def innerResourceInstanceMethod(*args, **kwargs): resourceInstanceName = methodClassName[:-len( FlaskManager.KW_SCHEDULER_RESOURCE)] resourceInstanceName = f'{resourceInstanceName[0].lower()}{resourceInstanceName[1:]}' args = FlaskManager.getArgumentInFrontOfArgs( args, ReflectionHelper.getAttributeOrMethod( apiInstance.resource.scheduler, resourceInstanceName)) resourceInstance = args[0] methodReturn = None try: FlaskManager.validateArgs(args, requestClass, innerResourceInstanceMethod) methodReturn = resourceInstanceMethod(*args, **kwargs) except Exception as exception: FlaskManager.raiseGlobalException(exception, resourceInstance, resourceInstanceMethod) log.log(innerResourceInstanceMethod, f'Not possible to run {shedulerId} properly', exception=exception) return methodReturn ReflectionHelper.overrideSignatures(innerResourceInstanceMethod, resourceInstanceMethod) return innerResourceInstanceMethod
def __init__(self, status=None, message=None, logMessage=None, logResource=None, logResourceMethod=None): self.timeStamp = datetime.datetime.now() self.status = status if ObjectHelper.isNotNone( status) else DEFAULT_STATUS self.message = message if ObjectHelper.isNotEmpty( message ) else DEFAULT_MESSAGE if 500 <= self.status else self.status.enumName self.verb = safellyGetVerb() self.url = safellyGetUrl() self.logMessage = logMessage if logMessage else DEFAULT_LOG_MESSAGE self.logResource = logResource if logResource else DEFAULT_LOG_RESOURCE self.logResourceMethod = logResourceMethod if logResourceMethod else DEFAULT_LOG_RESOURCE_METHOD self.logPayload = self.getRequestBody()
def getObjectAsDictionary(instance, fieldsToExpand=[EXPAND_ALL_FIELDS], visitedIdInstances=None): # print(instance) if ObjectHelper.isNone(visitedIdInstances): visitedIdInstances = [] if ObjectHelper.isNativeClassInstance(instance) or ObjectHelper.isNone(instance): return instance if EnumAnnotation.isEnumItem(instance): return instance.enumValue if isDatetimeRelated(instance): return str(instance) # print(f'{instance} not in {visitedIdInstances}: {instance not in visitedIdInstances}') isVisitedInstance = id(instance) in visitedIdInstances innerVisitedIdInstances = [*visitedIdInstances.copy()] if ObjectHelper.isDictionary(instance) and not isVisitedInstance : # for key,value in instance.items(): # instance[key] = getObjectAsDictionary(value, visitedIdInstances=innerVisitedIdInstances) # return instance return {key: getObjectAsDictionary(value, visitedIdInstances=innerVisitedIdInstances) for key, value in instance.items() } elif isSerializerCollection(instance): objectValueList = [] for innerObject in instance : innerAttributeValue = getObjectAsDictionary(innerObject, visitedIdInstances=innerVisitedIdInstances) if ObjectHelper.isNotNone(innerAttributeValue): objectValueList.append(innerAttributeValue) return objectValueList elif not isVisitedInstance : jsonInstance = {} try : # print(id(instance)) innerVisitedIdInstances.append(id(instance)) atributeNameList = getAttributeNameList_andPleaseSomeoneSlapTheFaceOfTheGuyWhoDidItInSqlAlchemy(instance.__class__) for attributeName in atributeNameList : attributeValue = getattr(instance, attributeName) if ReflectionHelper.isNotMethodInstance(attributeValue): jsonInstance[attributeName] = getObjectAsDictionary(attributeValue, visitedIdInstances=innerVisitedIdInstances) else : jsonInstance[attributeName] = None except Exception as exception : log.debug(getObjectAsDictionary, f'Not possible to get attribute name list from {ReflectionHelper.getName(ReflectionHelper.getClass(instance, muteLogs=True), muteLogs=True)}', exception=exception) if ObjectHelper.isNotEmpty(jsonInstance): return jsonInstance return str(instance)
def handleLogErrorException(exception, resourceInstance, resourceInstanceMethod, apiInstance): if not (isinstance(exception.__class__, GlobalException) or GlobalException.__name__ == exception.__class__.__name__): log.warning( handleLogErrorException, f'Failed to excecute {resourceInstanceMethod.__name__} method due to {exception.__class__.__name__} exception', exception=exception) message = None status = None logMessage = None if (isinstance(exception.__class__, NoAuthorizationError) or NoAuthorizationError.__name__ == exception.__class__.__name__ or isinstance(exception.__class__, RevokedTokenError) or RevokedTokenError.__name__ == exception.__class__.__name__ or isinstance(exception.__class__, ExpiredSignatureError) or ExpiredSignatureError.__name__ == exception.__class__.__name__): if not message: message = c.NOTHING message += str(exception) status = HttpStatus.UNAUTHORIZED if ObjectHelper.isNotEmpty(str(exception)): logMessage = str(exception) exception = GlobalException(message=message, logMessage=logMessage, logResource=resourceInstance, logResourceMethod=resourceInstanceMethod, status=status) try: if not exception.logResource or c.NOTHING == exception.logResource or not resourceInstance == exception.logResource: exception.logResource = resourceInstance if not exception.logResourceMethod or c.NOTHING == exception.logResourceMethod or not resourceInstanceMethod == exception.logResourceMethod: exception.logResourceMethod = resourceInstanceMethod httpErrorLog = ErrorLog.ErrorLog() httpErrorLog.override(exception) apiInstance.repository.saveAndCommit(httpErrorLog) except Exception as errorLogException: log.warning(resourceInstance.__class__, f'Failed to persist {ErrorLog.ErrorLog.__name__}', exception=errorLogException) return exception
def fromDtoToModel() : # arrange mockedDatetimeAsString = '2021-03-11 08:30:00' mockedDateAsString = mockedDatetimeAsString.split()[0] mockedTimeAsString = mockedDatetimeAsString.split()[1] instance = DateTimeTestResponseDto( beginAtDatetime = mockedDatetimeAsString, endAtDatetime = mockedDatetimeAsString, beginAtDate = mockedDateAsString, endAtDate = mockedDateAsString, beginAtTime = mockedTimeAsString, endAtTime = mockedTimeAsString, intervalTime = mockedDatetimeAsString, timedelta = mockedTimeAsString ) # log.prettyPython(fromModelToDto, 'instance', Serializer.getObjectAsDictionary(instance), logLevel=log.DEBUG) instanceList = [ instance, instance ] # act toAssert = Serializer.convertFromObjectToObject(instance, DateTimeTest) listToAssert = Serializer.convertFromObjectToObject(instanceList, [[DateTimeTest]]) # log.prettyPython(fromDtoToModel, 'toAssert', Serializer.getObjectAsDictionary(toAssert), logLevel=log.DEBUG) # log.prettyPython(fromModelToDto, 'listToAssert', Serializer.getObjectAsDictionary(listToAssert), logLevel=log.DEBUG) # assert assert ObjectHelper.isNotEmpty(toAssert) assert datetime.datetime == type(toAssert.beginAtDatetime) assert datetime.datetime == type(toAssert.endAtDatetime) assert datetime.date == type(toAssert.beginAtDate) assert datetime.date == type(toAssert.endAtDate) assert datetime.time == type(toAssert.beginAtTime) assert datetime.time == type(toAssert.endAtTime) assert datetime.datetime == type(toAssert.intervalTime) assert datetime.timedelta == type(toAssert.timedelta) assert ObjectHelper.equals( { 'beginAtDate': '2021-03-11', 'beginAtDatetime': '2021-03-11 08:30:00', 'beginAtTime': '08:30:00', 'endAtDate': '2021-03-11', 'endAtDatetime': '2021-03-11 08:30:00', 'endAtTime': '08:30:00', 'id': None, 'intervalTime': '2021-03-11 08:30:00', 'timedelta': '08:30:00' }, Serializer.getObjectAsDictionary(toAssert), ignoreKeyList = [ 'timedelta' ] ) assert ObjectHelper.isNotEmpty(listToAssert) assert ObjectHelper.equals( [ { 'beginAtDate': '2021-03-11', 'beginAtDatetime': '2021-03-11 08:30:00', 'beginAtTime': '08:30:00', 'endAtDate': '2021-03-11', 'endAtDatetime': '2021-03-11 08:30:00', 'endAtTime': '08:30:00', 'id': None, 'intervalTime': '2021-03-11 08:30:00', 'timedelta': '08:30:00' }, { 'beginAtDate': '2021-03-11', 'beginAtDatetime': '2021-03-11 08:30:00', 'beginAtTime': '08:30:00', 'endAtDate': '2021-03-11', 'endAtDatetime': '2021-03-11 08:30:00', 'endAtTime': '08:30:00', 'id': None, 'intervalTime': '2021-03-11 08:30:00', 'timedelta': '08:30:00' } ], Serializer.getObjectAsDictionary(listToAssert), ignoreKeyList = [ 'timedelta' ] )
def innerMethodWrapper(resourceMethod, *innerMethodArgs, **innerMethodKwargs): log.wrapper(SchedulerMethod, f'''wrapping {resourceMethod.__name__}''') apiInstance = FlaskManager.getApi() methodClassName = ReflectionHelper.getMethodClassName(resourceMethod) methodName = ReflectionHelper.getName(resourceMethod) methodKwargs['id'] = methodKwargs.get( 'id', f'{methodClassName}{c.DOT}{methodName}') instancesUpTo = methodKwargs.pop('instancesUpTo', 1) weekDays = methodKwargs.pop('weekDays', None) resourceMethod.disabled = disable resourceMethod.shedulerId = methodKwargs['id'] resourceMethod.muteLogs = muteLogs or ConverterStatic.getValueOrDefault( apiInstance.globals.getApiSetting( ConfigurationKeyConstant.API_SCHEDULER_MUTE_LOGS), DEFAUTL_MUTE_LOGS) if ObjectHelper.isNotEmpty( methodArgs ) and SchedulerType.CRON == methodArgs[0] and ObjectHelper.isNotNone( weekDays) and StringHelper.isNotBlank(weekDays): methodKwargs['day_of_week'] = weekDays if ObjectHelper.isNotNone(instancesUpTo): methodKwargs['max_instances'] = instancesUpTo shedulerArgs = [*methodArgs] shedulerKwargs = {**methodKwargs} @apiInstance.schedulerManager.task(*shedulerArgs, **shedulerKwargs) def innerResourceInstanceMethod(*args, **kwargs): resourceInstanceName = methodClassName[:-len( FlaskManager.KW_SCHEDULER_RESOURCE)] resourceInstanceName = f'{resourceInstanceName[0].lower()}{resourceInstanceName[1:]}' args = FlaskManager.getArgumentInFrontOfArgs( args, ReflectionHelper.getAttributeOrMethod( apiInstance.resource.scheduler, resourceInstanceName)) resourceInstance = args[0] muteLogs = resourceInstance.muteLogs or resourceMethod.muteLogs if resourceInstance.enabled and not resourceInstance.disabled and not resourceMethod.disabled: if not muteLogs: log.debug( resourceMethod, f'{resourceMethod.shedulerId} scheduler started with args={methodArgs} and kwargs={methodKwargs}' ) methodReturn = None try: FlaskManager.validateArgs(args, requestClass, innerResourceInstanceMethod) methodReturn = resourceMethod(*args, **kwargs) except Exception as exception: if not muteLogs: log.warning( resourceMethod, f'Not possible to run {resourceMethod.shedulerId} properly', exception=exception, muteStackTrace=True) FlaskManager.raiseAndPersistGlobalException( exception, resourceInstance, resourceMethod) if not muteLogs: log.debug( resourceMethod, f'{resourceMethod.shedulerId} scheduler finished') return methodReturn if not muteLogs: log.warning( resourceMethod, f'{resourceMethod.shedulerId} scheduler didn{c.SINGLE_QUOTE}t started. {"Schedulers are disabled" if not resourceInstance.enabled else "This scheduler is disabled" if resourceInstance.disabled else "This scheduler method is disabled"}' ) ReflectionHelper.overrideSignatures(innerResourceInstanceMethod, resourceMethod) resourceMethod.shedulerId = methodKwargs.get('id') innerResourceInstanceMethod.disable = resourceMethodDisable innerResourceInstanceMethod.muteLogs = resourceMethodMuteLogs return innerResourceInstanceMethod