def handleSecuredControllerMethod(args, kwargs, contentType, resourceInstance, resourceInstanceMethod, contextRequired, apiKeyRequired, roleRequired, requestHeaderClass, requestParamClass, requestClass, logRequest, muteStacktraceOnBusinessRuleException): contextList = SecurityManager.getContext() if not any(role in set(contextList) for role in roleRequired): raise GlobalException( message='Role not allowed', logMessage= f'''Roles {contextList} trying to access denied resourse. Allowed roles {roleRequired}''', status=HttpStatus.FORBIDDEN) elif ObjectHelper.isNotEmptyCollection(apiKeyRequired): return handleLockedByApiKeyControllerMethod( args, kwargs, contentType, resourceInstance, resourceInstanceMethod, contextRequired, apiKeyRequired, requestHeaderClass, requestParamClass, requestClass, logRequest, muteStacktraceOnBusinessRuleException) elif ObjectHelper.isNotEmptyCollection(contextRequired): return handleSessionedControllerMethod( args, kwargs, contentType, resourceInstance, resourceInstanceMethod, contextRequired, requestHeaderClass, requestParamClass, requestClass, logRequest, muteStacktraceOnBusinessRuleException) return handleControllerMethod(args, kwargs, contentType, resourceInstance, resourceInstanceMethod, requestHeaderClass, requestParamClass, requestClass, logRequest, muteStacktraceOnBusinessRuleException)
def handleAnyControllerMethodRequest( args, kwargs, contentType, resourceInstance, resourceInstanceMethod, contextRequired, apiKeyRequired, roleRequired, requestHeaderClass, requestParamClass, requestClass, logRequest, muteStacktraceOnBusinessRuleException): if ObjectHelper.isNotEmptyCollection(roleRequired): return handleSecuredControllerMethod( args, kwargs, contentType, resourceInstance, resourceInstanceMethod, contextRequired, apiKeyRequired, roleRequired, requestHeaderClass, requestParamClass, requestClass, logRequest, muteStacktraceOnBusinessRuleException) elif ObjectHelper.isNotEmptyCollection(apiKeyRequired): return handleLockedByApiKeyControllerMethod( args, kwargs, contentType, resourceInstance, resourceInstanceMethod, contextRequired, apiKeyRequired, requestHeaderClass, requestParamClass, requestClass, logRequest, muteStacktraceOnBusinessRuleException) elif ObjectHelper.isNotEmptyCollection(contextRequired): return handleSessionedControllerMethod( args, kwargs, contentType, resourceInstance, resourceInstanceMethod, contextRequired, requestHeaderClass, requestParamClass, requestClass, logRequest, muteStacktraceOnBusinessRuleException) return handleControllerMethod(args, kwargs, contentType, resourceInstance, resourceInstanceMethod, requestHeaderClass, requestParamClass, requestClass, logRequest, muteStacktraceOnBusinessRuleException)
def getCurrentUser(userClass=None, apiInstance=None): currentUsert = get_current_user() if ObjectHelper.isNotNone(currentUsert): return currentUsert else: rawJwt = getJwtBody() identity = getIdentity(rawJwt=rawJwt) context = getContext(rawJwt=rawJwt) data = getData(rawJwt=rawJwt) if ObjectHelper.isNone(userClass): return { JwtConstant.KW_IDENTITY: identity, JwtConstant.KW_CONTEXT: context, JwtConstant.KW_DATA: data } else: currentUsert = userClass() currentUsert._contextInfo = { JwtConstant.KW_IDENTITY: identity, JwtConstant.KW_CONTEXT: context } for attributeName in data: if ReflectionHelper.hasAttributeOrMethod( currentUsert, attributeName): ReflectionHelper.setAttributeOrMethod( currentUsert, attributeName, data.get(attributeName)) return currentUsert
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) return valuesAsDictionary
def getConnectArgs(self, connectArgs): if ObjectHelper.isNone(connectArgs): connectArgs = self.globals.getSetting( f'{self.KW_API}{c.DOT}{self.KW_DATABASE}{c.DOT}{self.KW_REPOSITORY_SETTINGS}' ) connectArgs = {} if ObjectHelper.isNotDictionary( connectArgs) else connectArgs return connectArgs
def getExceptionTextWithoutDotAtTheEnd(exception): if ObjectHelper.isNone(exception): return "Unknown" exceptionText = str(exception) while ObjectHelper.isNeitherNoneNorBlank( exceptionText) and c.DOT == exceptionText[-1]: exceptionText = exceptionText[:-1] return exceptionText
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 findAllByQueryAndCommit(self, query, modelClass): if ObjectHelper.isNotNone(query): objectList = self.session.query(modelClass).filter_by( ** {k: v for k, v in query.items() if ObjectHelper.isNotNone(v)}).all() self.session.commit() return objectList
def validateKeyAndTypeNotNone(self, dto): if ObjectHelper.isNone(dto.key): raise GlobalException.GlobalException( message=f'''The ContactDto.key '{dto.key}' cannot be None''', status=HttpStatus.BAD_REQUEST) if ObjectHelper.isNone(dto.type): raise GlobalException.GlobalException( message=f'''The ContactDto.type '{dto.type}' cannot be None''', status=HttpStatus.BAD_REQUEST)
def validateAndReturnResponse(completeResponse): if (ObjectHelper.isNotTuple(completeResponse) or not 3 == len(completeResponse)) or (ObjectHelper.isNotDictionary( completeResponse[1])) or (not isinstance( HttpStatus.map(completeResponse[-1]), EnumItem)): log.debug(validateAndReturnResponse, f'Invalid completeResponse: {completeResponse}') raise Exception('Invalid complete response') return completeResponse
def validateBodyAsJson(requestBodyAsJson, requestClass): if ObjectHelper.isNotNone(requestClass): requestBodyAsJsonIsList = ObjectHelper.isList(requestBodyAsJson) requestClassIsList = ObjectHelper.isList( requestClass) and ObjectHelper.isList(requestClass[0]) if not ((requestBodyAsJsonIsList and requestClassIsList) or (not requestBodyAsJsonIsList and not requestClassIsList)): raise GlobalException(message='Bad request', logMessage='Bad request', status=HttpStatus.BAD_REQUEST)
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 equal_whenDictionary(): #arrange firstDict = {'b': 'c', 'a': 'd'} secondDict = {'a': 'd', 'b': 'c'} #act firstDictSorted = ObjectHelper.sortIt(firstDict) secondDictSorted = ObjectHelper.sortIt(secondDict) #assert assert firstDictSorted == secondDictSorted
def getTag(self, link, soupBody=None): result = None if ObjectHelper.isNotNone(link): for font in GoogleSearchConstants.POSSIBLE_FONTS: if link.startswith(font): result = self.getResult( soup.find_all( GoogleSearchConstants.POSSIBLE_FONTS[font][ GoogleSearchConstants.KEY_TAG], GoogleSearchConstants.POSSIBLE_FONTS[font][ GoogleSearchConstants.KEY_ATTRIBUTE])) break return result if ObjectHelper.isNotNone(result) else soupBody
def mustIgnoreKeyCorrectly(): # arrange expected = {**{}, **DICTIONARY_INSTANCE} anotherDictionaryInstance = {**{}, **DICTIONARY_INSTANCE} IGNORABLE_KEY = 'ignorableKey' anotherDictionaryInstance[IGNORABLE_KEY] = 'ignorableValue' # act toAssert = ObjectHelper.filterIgnoreKeyList(anotherDictionaryInstance, [IGNORABLE_KEY]) # assert assert ObjectHelper.equals(expected, toAssert)
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 innerResourceInstanceMethod(*args, **kwargs): # r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # r.headers["Pragma"] = "no-cache" # r.headers["Expires"] = "0" # r.headers['Cache-Control'] = 'public, max-age=0' resourceInstance = args[0] completeResponse = None try: if ObjectHelper.isNotEmptyCollection(roleRequired): completeResponse = securedControllerMethod( args, kwargs, consumes, resourceInstance, resourceInstanceMethod, roleRequired, requestHeaderClass, requestParamClass, requestClass, logRequest) else: completeResponse = publicControllerMethod( args, kwargs, consumes, resourceInstance, resourceInstanceMethod, requestHeaderClass, requestParamClass, requestClass, logRequest) # print(f'completeResponse: {completeResponse}') validateResponseClass(responseClass, completeResponse) except Exception as exception: # print(exception) completeResponse = getCompleteResponseByException( exception, resourceInstance, resourceInstanceMethod) ###- request.method: GET ###- request.url: http://127.0.0.1:5000/alert/dingding/test?x=y ###- request.base_url: http://127.0.0.1:5000/alert/dingding/test ###- request.url_charset: utf-8 ###- request.url_root: http://127.0.0.1:5000/ ###- str(request.url_rule): /alert/dingding/test ###- request.host_url: http://127.0.0.1:5000/ ###- request.host: 127.0.0.1:5000 ###- request.script_root: ###- request.path: /alert/dingding/test ###- request.full_path: /alert/dingding/test?x=y ###- request.args: ImmutableMultiDict([('x', 'y')]) ###- request.args.get('x'): y controllerResponse = completeResponse[0] if ObjectHelper.isNotNone( completeResponse[0]) else { 'message': completeResponse[1].enumName } status = completeResponse[1] if logResponse: log.prettyJson(resourceInstanceMethod, 'bodyResponse', json.loads( Serializer.jsonifyIt(controllerResponse)), condition=logResponse, logLevel=log.DEBUG) return jsonifyResponse(controllerResponse, produces, status)
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 osIdentifierTest() : # arrange # act isWindows = EnvironmentHelper.isWindows() isLinux = EnvironmentHelper.isLinux() # assert assert ObjectHelper.isNotNone(isWindows) assert ObjectHelper.isNotNone(isLinux) assert ObjectHelper.isNativeClassInstance(isWindows) assert ObjectHelper.isNativeClassInstance(isLinux) assert bool == type(isWindows) assert bool == type(isLinux) assert isLinux or isWindows
def importModule(resourceModuleName, muteLogs=False, reload=False, ignoreList=IGNORE_MODULES, required=False): if resourceModuleName not in ignoreList: importException = None try: if reload: IMPORT_CASHE[resourceModuleName] = importlib.reload( resourceModuleName) elif (resourceModuleName not in IMPORT_CASHE or required and ObjectHelper.isNone( IMPORT_CASHE.get(resourceModuleName))): IMPORT_CASHE[resourceModuleName] = importlib.import_module( resourceModuleName) except Exception as exception: importException = exception if not muteLogs: log.log( importModule, f'Not possible to import "{resourceModuleName}" module. Going for a second attempt', exception=exception) try: IMPORT_CASHE[resourceModuleName] = __import__( resourceModuleName) except Exception as innerException: importException = innerException IMPORT_CASHE[resourceModuleName] = None if not muteLogs: log.log( importModule, f'Not possible to import "{resourceModuleName}" module in the second attempt either. Original cause: {str(exception)}. Returning "{IMPORT_CASHE.get(resourceModuleName)}" by default', exception=innerException) if required and ObjectHelper.isNone( IMPORT_CASHE.get(resourceModuleName)): if not importException: try: IMPORT_CASHE[resourceModuleName] = __import__( resourceModuleName) return IMPORT_CASHE.get(resourceModuleName) except Exception as exception: importException = exception dotSpaceCause = f'{c.DOT_SPACE_CAUSE}{getExceptionTextWithoutDotAtTheEnd(importException)}' raise Exception( f'Not possible to import module "{resourceModuleName}"{dotSpaceCause}{c.BLANK if dotSpaceCause.endswith(DOT_SPACE_CHECK_LOG_LEVEL_LOGS_FOR_MORE_INFORMATION) else DOT_SPACE_CHECK_LOG_LEVEL_LOGS_FOR_MORE_INFORMATION}' ) return IMPORT_CASHE.get(resourceModuleName)
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 raiseExceptionIfNeeded(clientResponse): status = FlaskUtil.safellyGetResponseStatus(clientResponse) ###- clientResponse.status_code if ObjectHelper.isNone(status) or 500 <= status: raise GlobalException( logMessage = getErrorMessage(clientResponse), url = FlaskUtil.safellyGetRequestUrlFromResponse(clientResponse), status = status, logHeaders = { 'requestHeaders': FlaskUtil.safellyGetRequestHeadersFromResponse(clientResponse), 'responseHeaders': FlaskUtil.safellyGetResponseHeaders(clientResponse) }, logPayload = { 'requestBody': FlaskUtil.safellyGetRequestJsonFromResponse(clientResponse), 'responseBody': FlaskUtil.safellyGetResponseJson(clientResponse) }, context = HttpDomain.CLIENT_CONTEXT ) elif 400 <= status: raise GlobalException( message = getErrorMessage(clientResponse), logMessage = HttpClientConstant.ERROR_AT_CLIENT_CALL_MESSAGE, url = FlaskUtil.safellyGetRequestUrlFromResponse(clientResponse), status = status, logHeaders = { 'requestHeaders': FlaskUtil.safellyGetRequestHeadersFromResponse(clientResponse), 'responseHeaders': FlaskUtil.safellyGetResponseHeaders(clientResponse) }, logPayload = { 'requestBody': FlaskUtil.safellyGetRequestJsonFromResponse(clientResponse), 'responseBody': FlaskUtil.safellyGetResponseJson(clientResponse) }, context = HttpDomain.CLIENT_CONTEXT )
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 appRun_whenEnvironmentIsLocalFromDevConfig_withSuccess(): # arrange muteLogs = False serverPort = 5002 process = getProcess( f'flask run --host=localhost --port={serverPort}', f'{CURRENT_PATH}{EnvironmentHelper.OS_SEPARATOR}apitests{EnvironmentHelper.OS_SEPARATOR}testone', muteLogs=muteLogs) BASE_URL = f'http://localhost:{serverPort}/dev-test-api' time.sleep(ESTIMATED_BUILD_TIME_IN_SECONDS) headers = { "User-Agent": "Mozilla/5.0 (X11; CrOS x86_64 12871.102.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36", 'Cache-Control': 'no-cache' } # act responseGetHealth = requests.post(BASE_URL + GET_ACTUATOR_HEALTH_CONTROLLER_TEST, json={'status': 'UP'}) # assert assert ObjectHelper.equals([{'status': 'UP'}], responseGetHealth.json()) assert 200 == responseGetHealth.status_code killProcesses(process)
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 search(self, search): googleSearchResponseList = self.client.googleSearch.rawTextSearch( search, 1, 10) # log.prettyPython(self.search, f'google query: {search}, googleSearchResponseList', googleSearchResponseList, logLevel=log.SUCCESS) dtoList = [] if ObjectHelper.isEmpty(googleSearchResponseList): title = 'Sorry' url = 'http://google.com.br' snippet = 'No relevante results were found' screenshotName = f'none.png' dtoList.append( GoogleSearchDto.GoogleSearchResponseDto( title=title, url=url, snippet=snippet, suggestedText= f'''*Title:* {title}{c.NEW_LINE}*Link:* {url}{c.NEW_LINE}*Snipet:* {snippet}''', screenshotName=screenshotName)) else: for googleSearchResponse in googleSearchResponseList: title = googleSearchResponse.get('title') url = googleSearchResponse.get('link') snippet = googleSearchResponse.get('snippet') screenshotName = f'{str(time.time()).replace(c.DOT,c.BLANK)}.png' # self.takeScreenshot(screenshotName, url) dtoList.append( GoogleSearchDto.GoogleSearchResponseDto( title=title, url=url, snippet=snippet, # suggestedText = f'''Title: {title.replace(c.NEW_LINE, c.SPACE)}{c.SPACE_DASH_SPACE *3}Link: {url}{c.SPACE_DASH_SPACE *3}Snipet: {snippet.replace(c.NEW_LINE, c.SPACE)}''', suggestedText= f'''*Title:* {title}{c.NEW_LINE}*Link:* {url}{c.NEW_LINE}*Snipet:* {snippet}''', screenshotName=screenshotName)) return dtoList
def innerResourceInstanceMethod(*args,**kwargs) : resourceInstance = args[0] completeResponse = None if logRequest : log.prettyJson( resourceInstanceMethod, 'bodyRequest', json.loads(Serializer.jsonifyIt(args[1:])), condition = logRequest, logLevel = log.DEBUG ) try : FlaskManager.validateKwargs( kwargs, resourceInstance, innerResourceInstanceMethod, requestHeaderClass = requestHeaderClass, requestParamClass = requestParamClass ) FlaskManager.validateArgs(args, requestClass, innerResourceInstanceMethod) completeResponse = resourceInstanceMethod(*args,**kwargs) FlaskManager.validateResponseClass(responseClass, completeResponse) except Exception as exception : log.warning(innerResourceInstanceMethod, 'Not posssible to complete request', exception=exception) raise exception controllerResponse = completeResponse[0] if ObjectHelper.isNotNone(completeResponse[0]) else {'message' : completeResponse[1].enumName} if logResponse : log.prettyJson( resourceInstanceMethod, 'bodyResponse', json.loads(Serializer.jsonifyIt(controllerResponse)), condition = logResponse, logLevel = log.DEBUG ) return completeResponse[0]
def getCurrentSession(sessionClass=None, apiInstance=None): apiInstance = retrieveApiInstance(apiInstance=apiInstance) rawJwt = getJwtBody(apiInstance=apiInstance) identity = getIdentity(rawJwt=rawJwt, apiInstance=apiInstance) context = getContext(rawJwt=rawJwt, apiInstance=apiInstance) data = getData(rawJwt=rawJwt, apiInstance=apiInstance) if ObjectHelper.isNone(sessionClass): return { JwtConstant.KW_IDENTITY: identity, JwtConstant.KW_CONTEXT: context, JwtConstant.KW_DATA: data } else: currentSession = sessionClass() currentSession._contextInfo = { JwtConstant.KW_IDENTITY: identity, JwtConstant.KW_CONTEXT: context } for attributeName in data: if ReflectionHelper.hasAttributeOrMethod(currentSession, attributeName): ReflectionHelper.setAttributeOrMethod(currentSession, attributeName, data.get(attributeName)) return currentSession
def __init__(self, verb, *args, **kwargs): if ObjectHelper.isNone(verb): raise Exception('Http client event verb cannot be none') Exception.__init__(self, f'Http client {verb} event') self.verb = verb self.args = args self.kwargs = kwargs
def mustLogPretyPythonWithColors(): # Arrange # log.log(mustLogPretyPythonWithColors, f'type({MyClass}): {type(MyClass)}') # log.log(mustLogPretyPythonWithColors, f'type({MyClass}).__name__: {type(MyClass).__name__}') # log.log(mustLogPretyPythonWithColors, f'type({MyClass().myMethod}): {type(MyClass().myMethod)}') # log.log(mustLogPretyPythonWithColors, f'type({MyClass().myMethod}).__name__: {type(MyClass().myMethod).__name__}') # log.log(mustLogPretyPythonWithColors, f'type({myFunction}): {type(myFunction)}') # log.log(mustLogPretyPythonWithColors, f'type({myFunction}).__name__: {type(myFunction).__name__}') # log.log(mustLogPretyPythonWithColors, f'type({log}): {type(log)}') # log.log(mustLogPretyPythonWithColors, f'type({log}).__name__: {type(log).__name__}') dictionaryInstance = { **{ 'class': MyClass, 'method': MyClass().myMethod, 'value': MyClass().myMethod(), 'function': myFunction, 'otherValue': myFunction(1.1), 'module': log }, **DICTIONARY_INSTANCE } exception = None # Act try: log.prettyPython(mustLogPretyPythonWithColors, 'prettyPython', dictionaryInstance) except Exception as e: log.failure(mustLogPretyPythonWithColors, 'Failed to log prety python in this method call', e) exception = e # Assert assert ObjectHelper.isNone(exception)