def innerMethodWrapper(resourceInstanceMethod, *args, **kwargs): def myPrint(resourceInstance, abcd): url = 2 if ObjectHelper.isNotNone(abcd): url = resourceInstance.url + clientMethodUrl + abcd return url def innerResourceInstanceMethod(*args, **kwargs): resourceInstance = args[0] completeResponse = 1 httpClientEvent = getHttpClientEvent(resourceInstanceMethod, *args, **kwargs) try: return myPrint(resourceInstance, *httpClientEvent.args, **httpClientEvent.kwargs) except Exception as exception: print(exception) completeResponse = 3 return completeResponse return completeResponse ReflectionHelper.overrideSignatures(innerResourceInstanceMethod, resourceInstanceMethod) innerResourceInstanceMethod.url = clientMethodUrl return innerResourceInstanceMethod
def Wrapper(OuterClass, *args, **kwargs): log.wrapper(HttpClient,f'''wrapping {OuterClass.__name__}''') class InnerClass(OuterClass): url = clientUrl headers = clientHeaders timeout = clientTimeout logRequest = clientLogRequest logResponse = clientLogResponse def __init__(self,*args, **kwargs): log.wrapper(OuterClass,f'in {InnerClass.__name__}.__init__(*{args},**{kwargs})') apiInstance = FlaskManager.getApi() OuterClass.__init__(self,*args, **kwargs) self.globals = apiInstance.globals def options(self, *args, **kwargs): raise HttpClientEvent(HttpDomain.Verb.OPTIONS, *args, **kwargs) def get(self, *args, **kwargs): raise HttpClientEvent(HttpDomain.Verb.GET, *args, **kwargs) def post(self, *args, **kwargs): raise HttpClientEvent(HttpDomain.Verb.POST, *args, **kwargs) def put(self, *args, **kwargs): raise HttpClientEvent(HttpDomain.Verb.PUT, *args, **kwargs) def patch(self, *args, **kwargs): raise HttpClientEvent(HttpDomain.Verb.PATCH, *args, **kwargs) def delete(self, *args, **kwargs): raise HttpClientEvent(HttpDomain.Verb.DELETE, *args, **kwargs) ReflectionHelper.overrideSignatures(InnerClass, OuterClass) return InnerClass
def wrapper(function, *args, **kwargs): log.wrapper( wrapper, f'Wrapping {function} function with (*{args} args and **{kwargs} kwargs)' ) def wrapedFunction(*args, **kwargs): try: functionReturn = function(*args, **kwargs) except Exception as exception: if isinstance(exception, GlobalException): raise exception logMessage = str(exception) if StringHelper.isNotBlank( str(exception)) else LOG_MESSAGE_NOT_PRESENT functionName = ReflectionHelper.getName( function, typeName=c.TYPE_FUNCTION) log.wrapper( EncapsulateItWithGlobalException, f'''Failed to execute "{functionName}(args={args}, kwargs={kwargs})" {c.TYPE_FUNCTION} call''', exception) raise GlobalException( message=message, logMessage=logMessage, logResource=ReflectionHelper.getParentClass(function), logResourceMethod=function, status=HttpStatus.map( encapsulateItWithGlobalExceptionStatus).enumValue) return functionReturn ReflectionHelper.overrideSignatures(wrapedFunction, function) return wrapedFunction
def jwtRefreshRequired(function, *args, **kwargs): def innerFunction(*args, **kwargs): ###- arguments=args[0] --> python weardnes in it's full glory retrieveApiInstance( arguments=args[0]).sessionManager.validateRefreshSession() functionReturn = function(*args, **kwargs) return functionReturn ReflectionHelper.overrideSignatures(innerFunction, function) return innerFunction
def Wrapper(OuterClass, *args, **kwargs): log.debug(Client,f'''wrapping {OuterClass.__name__}''') class InnerClass(OuterClass): url = controllerUrl def __init__(self,*args,**kwargs): log.debug(OuterClass,f'in {InnerClass.__name__}.__init__(*{args},**{kwargs})') apiInstance = FlaskManager.getApi() OuterClass.__init__(self,*args,**kwargs) self.globals = apiInstance.globals ReflectionHelper.overrideSignatures(InnerClass, OuterClass) return InnerClass
def Wrapper(OuterClass, *args, **kwargs): log.wrapper(Repository,f'''wrapping {OuterClass.__name__}''') class InnerClass(OuterClass): model = repositoryModel def __init__(self,*args,**kwargs): log.wrapper(OuterClass,f'in {InnerClass.__name__}.__init__(*{args},**{kwargs})') OuterClass.__init__(self,*args,**kwargs) apiInstance = FlaskManager.getApi() self.repository = apiInstance.repository self.globals = apiInstance.globals ReflectionHelper.overrideSignatures(InnerClass, OuterClass) return InnerClass
def innerMethodWrapper(resourceInstanceMethod,*args,**kwargs) : log.debug(ValidatorMethod,f'''wrapping {resourceInstanceMethod.__name__}''') def innerResourceInstanceMethod(*args,**kwargs) : resourceInstance = args[0] try : FlaskManager.validateArgs(args,requestClass,innerResourceInstanceMethod) methodReturn = resourceInstanceMethod(*args,**kwargs) except Exception as exception : FlaskManager.raiseGlobalException(exception, resourceInstance, resourceInstanceMethod) return methodReturn ReflectionHelper.overrideSignatures(innerResourceInstanceMethod, resourceInstanceMethod) return innerResourceInstanceMethod
def Wrapper(OuterClass, *args, **kwargs): log.debug(Validator,f'''wrapping {OuterClass.__name__}''') class InnerClass(OuterClass): def __init__(self,*args,**kwargs): log.debug(OuterClass,f'in {InnerClass.__name__}.__init__(*{args},**{kwargs})') OuterClass.__init__(self,*args,**kwargs) apiInstance = FlaskManager.getApi() self.service = apiInstance.resource.service self.validator = apiInstance.resource.validator self.helper = apiInstance.resource.helper self.converter = apiInstance.resource.converter ReflectionHelper.overrideSignatures(InnerClass, OuterClass) return InnerClass
def Wrapper(OuterClass, *args, **kwargs): log.debug(SimpleClient, f'''wrapping {OuterClass.__name__}''') class InnerClass(OuterClass): def __init__(self, *args, **kwargs): log.debug( OuterClass, f'in {InnerClass.__name__}.__init__(*{args},**{kwargs})') OuterClass.__init__(self, *args, **kwargs) self.globals = getApi().globals ReflectionHelper.overrideSignatures(InnerClass, OuterClass) return InnerClass
def Wrapper(OuterClass, *args, **kwargs): class InnerClass(OuterClass): url = clientUrl def __init__(self, *args, **kwargs): OuterClass.__init__(self, *args, **kwargs) def myPrint(self, *args, **kwargs): raise HttpClientEvent(*args, key=4, **kwargs) ReflectionHelper.overrideSignatures(InnerClass, OuterClass) print(InnerClass) return InnerClass
def innerMethodWrapper(resourceInstanceMethod,*args,**kwargs) : log.debug(ClientMethod,f'''wrapping {resourceInstanceMethod.__name__}''') 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] ReflectionHelper.overrideSignatures(innerResourceInstanceMethod, resourceInstanceMethod) innerResourceInstanceMethod.url = controllerMethodUrl innerResourceInstanceMethod.requestHeaderClass = controllerMethodRequestHeaderClass innerResourceInstanceMethod.requestParamClass = controllerMethodRequestParamClass innerResourceInstanceMethod.requestClass = controllerMethodRequestClass innerResourceInstanceMethod.responseClass = controllerMethodResponseClass innerResourceInstanceMethod.roleRequired = controllerMethodRoleRequired innerResourceInstanceMethod.produces = controllerMethodProduces innerResourceInstanceMethod.consumes = controllerMethodConsumes innerResourceInstanceMethod.logRequest = controllerMethodLogRequest innerResourceInstanceMethod.logResponse = controllerMethodLogResponse return innerResourceInstanceMethod
def Wrapper(OuterClass, *args, **kwargs): log.debug(Scheduler, f'''wrapping {OuterClass.__name__}''') class InnerClass(OuterClass): def __init__(self, *args, **kwargs): log.debug( OuterClass, f'in {InnerClass.__name__}.__init__(*{args},**{kwargs})') apiInstance = FlaskManager.getApi() OuterClass.__init__(self, *args, **kwargs) self.globals = apiInstance.globals self.service = apiInstance.resource.service ReflectionHelper.overrideSignatures(InnerClass, OuterClass) return InnerClass
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 Wrapper(OuterClass, *args, **kwargs): log.wrapper(Service,f'''wrapping {OuterClass.__name__}''') class InnerClass(OuterClass): def __init__(self,*args,**kwargs): log.wrapper(OuterClass,f'in {InnerClass.__name__}.__init__(*{args},**{kwargs})') apiInstance = FlaskManager.getApi() OuterClass.__init__(self,*args,**kwargs) self.service = apiInstance.resource.service self.client = apiInstance.resource.client self.repository = apiInstance.resource.repository self.validator = apiInstance.resource.validator self.mapper = apiInstance.resource.mapper self.helper = apiInstance.resource.helper self.converter = apiInstance.resource.converter self.globals = apiInstance.globals ReflectionHelper.overrideSignatures(InnerClass, OuterClass) return InnerClass
def innerMethodWrapper(resourceInstanceMethod, *args, **kwargs): log.wrapper(HelperMethod, f'''wrapping {resourceInstanceMethod.__name__}''') def innerResourceInstanceMethod(*args, **kwargs): resourceInstance = args[0] try: FlaskManager.validateArgs(args, requestClass, innerResourceInstanceMethod) args = FlaskManager.getArgsWithResponseClassInstanceAppended( args, responseClass) methodReturn = resourceInstanceMethod(*args, **kwargs) except Exception as exception: FlaskManager.raiseAndPersistGlobalException( exception, resourceInstance, resourceInstanceMethod) return methodReturn ReflectionHelper.overrideSignatures(innerResourceInstanceMethod, resourceInstanceMethod) return innerResourceInstanceMethod
def Wrapper(OuterClass, *args, **kwargs): log.wrapper(Client, f'''wrapping {OuterClass.__name__}''') class InnerClass(OuterClass): url = clientUrl headers = clientHeaders timeout = clientTimeout logRequest = clientLogRequest logResponse = clientLogResponse def __init__(self, *args, **kwargs): log.wrapper( OuterClass, f'in {InnerClass.__name__}.__init__(*{args},**{kwargs})') apiInstance = FlaskManager.getApi() OuterClass.__init__(self, *args, **kwargs) self.globals = apiInstance.globals ReflectionHelper.overrideSignatures(InnerClass, OuterClass) return InnerClass
def innerMethodWrapper(resourceInstanceMethod, *args, **kwargs): log.wrapper(ClientMethod, f'''wrapping {resourceInstanceMethod.__name__}''') def innerResourceInstanceMethod(*args, **kwargs): resourceInstance = args[0] completeResponse = None try: FlaskManager.validateArgs(args, requestClass, resourceInstanceMethod) completeResponse = resourceInstanceMethod(*args, **kwargs) ###- This simple client cannot handle headers or anything this much elegant if ObjectHelper.isTuple( completeResponse) and 0 < len(completeResponse): completeResponse = completeResponse[0] except Exception as exception: log.log(innerResourceInstanceMethod, 'Failure at client method execution', exception=exception, muteStackTrace=True) raise exception return completeResponse ReflectionHelper.overrideSignatures(innerResourceInstanceMethod, resourceInstanceMethod) innerResourceInstanceMethod.url = clientMethodUrl innerResourceInstanceMethod.headers = clientMethodHeaders innerResourceInstanceMethod.requestHeaderClass = clientMethodRequestHeaderClass innerResourceInstanceMethod.requestParamClass = clientMethodRequestParamClass innerResourceInstanceMethod.requestClass = clientMethodRequestClass innerResourceInstanceMethod.responseClass = clientMethodResponseClass innerResourceInstanceMethod.returnOnlyBody = clientMethodReturnOnlyBody innerResourceInstanceMethod.timeout = clientMethodTimeout innerResourceInstanceMethod.propagateAuthorization = clientMethodPropagateAuthorization innerResourceInstanceMethod.propagateApiKey = clientMethodPropagateApiKey innerResourceInstanceMethod.propagateSession = clientMethodPropagateSession innerResourceInstanceMethod.produces = clientMethodProduces innerResourceInstanceMethod.consumes = clientMethodConsumes innerResourceInstanceMethod.logRequest = clientMethodLogRequest innerResourceInstanceMethod.logResponse = clientMethodLogResponse return innerResourceInstanceMethod
def Wrapper(OuterClass, *args, **kwargs): log.debug(Controller, f'''wrapping {OuterClass.__name__}''', None) class InnerClass(OuterClass, flask_restful.Resource): url = controllerUrl tag = controllerTag description = controllerDescription def __init__(self, *args, **kwargs): log.debug( OuterClass, f'in {InnerClass.__name__}.__init__(*{args},**{kwargs})', None) apiInstance = getApi() OuterClass.__init__(self) flask_restful.Resource.__init__(self, *args, **kwargs) self.service = apiInstance.resource.service self.globals = apiInstance.globals ReflectionHelper.overrideSignatures(InnerClass, OuterClass) return InnerClass
def Wrapper(OuterClass, *args, **kwargs): log.wrapper(Scheduler, f'''wrapping {OuterClass.__name__}''') class InnerClass(OuterClass): def __init__(self, *args, **kwargs): log.wrapper( OuterClass, f'in {InnerClass.__name__}.__init__(*{args},**{kwargs})') apiInstance = FlaskManager.getApi() OuterClass.__init__(self, *args, **kwargs) self.globals = apiInstance.globals self.service = apiInstance.resource.service self.enabled = self.globals.getApiSetting( ConfigurationKeyConstant.API_SCHEDULER_ENABLE) self.disabled = disable self.muteLogs = muteLogs or ConverterStatic.getValueOrDefault( self.globals.getApiSetting( ConfigurationKeyConstant.API_SCHEDULER_MUTE_LOGS), DEFAUTL_MUTE_LOGS) ReflectionHelper.overrideSignatures(InnerClass, OuterClass) return InnerClass
def Wrapper(OuterClass, *args, **kwargs): log.wrapper(Controller, f'''wrapping {OuterClass.__name__}''', None) class InnerClass(OuterClass, FlaskUtil.Resource): url = controllerUrl responseHeaders = controllerResponseHeaders tag = controllerTag description = controllerDescription logRequest = controllerLogRequest logResponse = controllerLogResponse def __init__(self, *args, **kwargs): log.wrapper( OuterClass, f'in {InnerClass.__name__}.__init__(*{args},**{kwargs})', None) apiInstance = FlaskUtil.getApi() OuterClass.__init__(self) FlaskUtil.Resource.__init__(self, *args, **kwargs) self.service = apiInstance.resource.service self.globals = apiInstance.globals ReflectionHelper.overrideSignatures(InnerClass, OuterClass) return InnerClass
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
def innerMethodWrapper(resourceInstanceMethod, *args, **kwargs): log.wrapper(ControllerMethod, f'''wrapping {resourceInstanceMethod.__name__}''', None) def innerResourceInstanceMethod(*args, **kwargs): f'''(*args, {FlaskUtil.KW_HEADERS}={{}}, {FlaskUtil.KW_PARAMETERS}={{}}, **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 log.info( resourceInstanceMethod, f'[CONTROLLER] {FlaskUtil.safellyGetVerb()} - {FlaskUtil.safellyGetUrl()}' ) try: completeResponse = handleAnyControllerMethodRequest( args, kwargs, consumes, resourceInstance, resourceInstanceMethod, contextRequired, apiKeyRequired, roleRequired, requestHeaderClass, requestParamClass, requestClass, logRequest, muteStacktraceOnBusinessRuleException) validateCompleteResponse(responseClass, completeResponse) except Exception as exception: log.log( innerResourceInstanceMethod, 'Failure at controller method execution. Getting complete response as exception', exception=exception, muteStackTrace=True) completeResponse = getCompleteResponseByException( exception, resourceInstance, resourceInstanceMethod, muteStacktraceOnBusinessRuleException) ###- 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 try: status = HttpStatus.map(completeResponse[-1]) additionalResponseHeaders = completeResponse[1] if ObjectHelper.isNotNone(resourceInstance.responseHeaders): additionalResponseHeaders = { **resourceInstance.responseHeaders, **additionalResponseHeaders } if ObjectHelper.isNotNone(responseHeaders): additionalResponseHeaders = { **responseHeaders, **additionalResponseHeaders } responseBody = completeResponse[0] if ObjectHelper.isNotNone( completeResponse[0]) else { 'message': status.enumName } httpResponse = FlaskUtil.buildHttpResponse( additionalResponseHeaders, responseBody, status.enumValue, produces) except Exception as exception: log.failure( innerResourceInstanceMethod, f'Failure while parsing complete response: {completeResponse}. Returning simplified version of it', exception, muteStackTrace=True) completeResponse = getCompleteResponseByException( Exception('Not possible to handle complete response'), resourceInstance, resourceInstanceMethod, muteStacktraceOnBusinessRuleException) httpResponse = FlaskUtil.buildHttpResponse( completeResponse[1], completeResponse[0], completeResponse[-1].enumValue, produces) try: if resourceInstance.logResponse or logResponse: log.prettyJson( resourceInstanceMethod, '[CONTROLLER] Response', { 'headers': FlaskUtil.safellyGetResponseHeaders(httpResponse), 'body': FlaskUtil.safellyGetFlaskResponseJson( httpResponse ), ###- json.loads(Serializer.jsonifyIt(responseBody)) 'status': status }, condition=True, logLevel=log.INFO) except Exception as exception: log.failure(innerResourceInstanceMethod, 'Not possible to log response properly', exception) return httpResponse ReflectionHelper.overrideSignatures(innerResourceInstanceMethod, resourceInstanceMethod) innerResourceInstanceMethod.url = controllerMethodUrl innerResourceInstanceMethod.requestHeaderClass = controllerMethodRequestHeaderClass innerResourceInstanceMethod.requestParamClass = controllerMethodRequestParamClass innerResourceInstanceMethod.requestClass = controllerMethodRequestClass innerResourceInstanceMethod.responseClass = controllerMethodResponseClass innerResourceInstanceMethod.responseHeaders = controllerMethodResponseHeaders innerResourceInstanceMethod.roleRequired = controllerMethodRoleRequired innerResourceInstanceMethod.apiKeyRequired = controllerMethodApiKeyRequired innerResourceInstanceMethod.contextRequired = controllerMethodSessionRequired innerResourceInstanceMethod.produces = controllerMethodProduces innerResourceInstanceMethod.consumes = controllerMethodConsumes innerResourceInstanceMethod.logRequest = controllerMethodLogRequest innerResourceInstanceMethod.logResponse = controllerMethodLogResponse innerResourceInstanceMethod.muteStacktraceOnBusinessRuleException = controllerMethodMuteStacktraceOnBusinessRuleException return innerResourceInstanceMethod
def innerMethodWrapper(resourceInstanceMethod, *args, **kwargs): log.debug(ControllerMethod, f'''wrapping {resourceInstanceMethod.__name__}''', None) 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) ReflectionHelper.overrideSignatures(innerResourceInstanceMethod, resourceInstanceMethod) innerResourceInstanceMethod.url = controllerMethodUrl innerResourceInstanceMethod.requestHeaderClass = controllerMethodRequestHeaderClass innerResourceInstanceMethod.requestParamClass = controllerMethodRequestParamClass innerResourceInstanceMethod.requestClass = controllerMethodRequestClass innerResourceInstanceMethod.responseClass = controllerMethodResponseClass innerResourceInstanceMethod.roleRequired = controllerMethodRoleRequired innerResourceInstanceMethod.produces = controllerMethodProduces innerResourceInstanceMethod.consumes = controllerMethodConsumes innerResourceInstanceMethod.logRequest = controllerMethodLogRequest innerResourceInstanceMethod.logResponse = controllerMethodLogResponse return innerResourceInstanceMethod
def Wrapper(OuterEnum, *args, **kwargs): def __raiseBadImplementation__(enumValue, enum=None): raise Exception( f'Not possible to implement "{enumValue}" enum value in {enum} enum' ) def __raiseEnumValueNotImplemented__(enumValue, enumClass=None, enumEqList=None, enumMap=None): raise Exception( f'Not possible to retrieve "{enumValue}" of type: {type(enumValue)} enum value from {ReflectionHelper.getName(enumClass)}: {enumEqList} enum. Enum.__enumMap__ = {enumMap}' ) if instanceLog: log.log(Enum, f'''wrapping {OuterEnum.__name__}''') class InnerEnum(OuterEnum, EnumClass): OuterEnum.__enumMap__ = {} OuterEnum.__enumEqList__ = [] def __init__(self, *args, **kwargs): originalClassAttributeValueList = ReflectionHelper.getAttributeNameList( OuterEnum) if instanceLog: log.prettyPython(OuterEnum, 'originalClassAttributeValueList', originalClassAttributeValueList) OuterEnum.__init__(self, *args, **kwargs) self.__associateReturnsTo__ = associateReturnsTo attributeDataList = ReflectionHelper.getAttributeDataList(self) if instanceLog: log.prettyPython(OuterEnum, 'attributeDataList', attributeDataList) for attribute, enumValue in attributeDataList: if enumValue not in ENUM_STATIC_METHOD_NAME_LIST and enumValue not in originalClassAttributeValueList: __raiseBadImplementation__(enumValue, enum=self) nativeClassDataList = [] attributeAttributeDataList = ReflectionHelper.getAttributeDataList( attribute) if instanceLog: log.prettyPython(OuterEnum, 'attributeAttributeDataList', attributeAttributeDataList) # print(f'type({attribute}): {type(attribute)}') association = ReflectionHelper.getAttributeOrMethod( attribute, self.__associateReturnsTo__, muteLogs=True) if type(association) is type(None): # print('type(association) is type(None)') ReflectionHelper.setAttributeOrMethod( attribute, ENUM_VALUE_AS_STRING_KEY, ENUM_ITEM_CLASS_DICTIONARY.get( type(enumValue))(enumValue)) nativeClassDataList = ReflectionHelper.getAttributeDataList( type(enumValue)()) # print(f'type({enumValue}): {type(enumValue)}, type({type(enumValue)}()): {type(type(enumValue)())}') else: # print('not type(association) is type(None)') ReflectionHelper.setAttributeOrMethod( attribute, ENUM_VALUE_AS_STRING_KEY, ENUM_ITEM_CLASS_DICTIONARY.get( type(association))(association)) nativeClassDataList = ReflectionHelper.getAttributeDataList( type(association)()) # print(f'type({association}): {type(association)}, type({type(association)}()): {type(type(association)())}') # print() attribute.enumValue.enumName = enumValue ReflectionHelper.setAttributeOrMethod( attribute, ENUM_NAME_AS_STRING_KEY, enumValue) if isinstance(attribute, EnumItem): # print(attribute, attribute.enumName, attribute) updateEnumItem( attribute, attribute.enumName, attribute) ###- so that __eq__ does not crash if not c.TYPE_FUNCTION == ReflectionHelper.getClassName( attribute): attribute.enumValue.__enumItemMap__ = attribute.__enumItemMap__ attribute.enumValue.__enumItemEqMap__ = attribute.__enumItemEqMap__ for dataInstance, dataName in attributeAttributeDataList: nativeData = False for _, name in nativeClassDataList: if dataName == name: nativeData = True break if not nativeData: ReflectionHelper.setAttributeOrMethod( attribute.enumValue, dataName, dataInstance) ReflectionHelper.setAttributeOrMethod( attribute.enumValue, ENUM_VALUE_AS_STRING_KEY, ReflectionHelper.getAttributeOrMethod( attribute, self.__associateReturnsTo__, muteLogs=True)) ReflectionHelper.setAttributeOrMethod( attribute.enumValue, ENUM_NAME_AS_STRING_KEY, enumValue) ReflectionHelper.setAttributeOrMethod( attribute.enumValue, ENUM_AS_STRING_KEY, self) if ObjectHelper.isEmpty(OuterEnum.__enumEqList__): for attribute, value in attributeDataList: # print(f'type({value}): {type(value)}') # print(f'type({attribute}): {type(attribute)}') valueAsString = str(attribute.enumValue) if valueAsString not in ENUM_STATIC_METHOD_NAME_LIST: if valueAsString not in self.__enumMap__: self.__enumMap__[ valueAsString] = attribute.enumValue ###- ReflectionHelper.getAttributeOrMethod(attribute, valueAsString, muteLogs=True) ###- attribute else: __raiseBadImplementation__(valueAsString, enum=self) if value not in self.__enumMap__: self.__enumMap__[value] = attribute elif not self.__enumMap__[value] == attribute: __raiseBadImplementation__(valueAsString, enum=self) self.__enumEqList__.append( f'{value}({self.__associateReturnsTo__}:{valueAsString})' ) def __eq__(self, other): return str(self) == str(other) def __ne__(self, other): return str(self) != str(other) def __str__(self): return StringHelper.join([ ReflectionHelper.getName(OuterEnum), c.COLON_SPACE, str(self.__enumEqList__) ]) def __repr__(self): return self.__str__() @staticmethod def map(enumItemOrEnumItemValue): if instanceLog: log.log( OuterEnum, f'''enumItemOrEnumItemValue: {enumItemOrEnumItemValue}''' ) if ObjectHelper.isNone(enumItemOrEnumItemValue): return enumItemOrEnumItemValue else: # try : # print(f'''not ReflectionHelper.hasAttributeOrMethod({enumItemOrEnumItemValue}, 'enumName') --> {str(enumItemOrEnumItemValue)}''') # except : # print(f'''ReflectionHelper.hasAttributeOrMethod({enumItemOrEnumItemValue}, 'enumName') --> {enumItemOrEnumItemValue.enumName}''') mappedEnum = OuterEnum.__enumMap__.get( str(enumItemOrEnumItemValue ) if not ReflectionHelper.hasAttributeOrMethod( enumItemOrEnumItemValue, 'enumName') else enumItemOrEnumItemValue.enumName) return mappedEnum if ObjectHelper.isNotNone( mappedEnum) else __raiseEnumValueNotImplemented__( enumItemOrEnumItemValue, enumClass=OuterEnum, enumEqList=OuterEnum.__enumEqList__, enumMap=OuterEnum.__enumMap__) ReflectionHelper.overrideSignatures(InnerEnum, OuterEnum) return InnerEnum
def innerMethodWrapper(resourceInstanceMethod,*args, **kwargs) : def options( resourceInstance, body = None, additionalUrl = None, params = None, headers = None, timeout = None, logRequest = False, **kwargs ): verb = HttpDomain.Verb.OPTIONS url, params, headers, body, timeout, logRequest = parseParameters( resourceInstance, clientMethodConfig, additionalUrl, params, headers, body, timeout, logRequest ) doLogRequest(verb, url, body, params, headers, logRequest) clientResponse = requests.options( url, params = params, headers = headers, json = body, timeout = timeout, **kwargs ) return clientResponse def get( resourceInstance, body = None, additionalUrl = None, params = None, headers = None, timeout = None, logRequest = False, **kwargs ): verb = HttpDomain.Verb.GET url, params, headers, body, timeout, logRequest = parseParameters( resourceInstance, clientMethodConfig, additionalUrl, params, headers, body, timeout, logRequest ) doLogRequest(verb, url, body, params, headers, logRequest) clientResponse = requests.get( url, params = params, headers = headers, json = body, timeout = timeout, **kwargs ) return clientResponse def post( resourceInstance, body = None, additionalUrl = None, headers = None, params = None, timeout = None, logRequest = False, **kwargs ): verb = HttpDomain.Verb.POST url, params, headers, body, timeout, logRequest = parseParameters( resourceInstance, clientMethodConfig, additionalUrl, params, headers, body, timeout, logRequest ) doLogRequest(verb, url, body, params, headers, logRequest) clientResponse = requests.post( url, params = params, headers = headers, json = body, timeout = timeout, **kwargs ) return clientResponse def put( resourceInstance, body = None, additionalUrl = None, headers = None, params = None, timeout = None, logRequest = False, **kwargs ): verb = HttpDomain.Verb.PUT url, params, headers, body, timeout, logRequest = parseParameters( resourceInstance, clientMethodConfig, additionalUrl, params, headers, body, timeout, logRequest ) doLogRequest(verb, url, body, params, headers, logRequest) clientResponse = requests.put( url, params = params, headers = headers, json = body, timeout = timeout, **kwargs ) return clientResponse def patch( resourceInstance, body = None, additionalUrl = None, headers = None, params = None, timeout = None, logRequest = False, **kwargs ): verb = HttpDomain.Verb.PATCH url, params, headers, body, timeout, logRequest = parseParameters( resourceInstance, clientMethodConfig, additionalUrl, params, headers, body, timeout, logRequest ) doLogRequest(verb, url, body, params, headers, logRequest) clientResponse = requests.patch( url, params = params, headers = headers, json = body, timeout = timeout, **kwargs ) return clientResponse def delete( resourceInstance, body = None, additionalUrl = None, headers = None, params = None, timeout = None, logRequest = False, **kwargs ): verb = HttpDomain.Verb.DELETE url, params, headers, body, timeout, logRequest = parseParameters( resourceInstance, clientMethodConfig, additionalUrl, params, headers, body, timeout, logRequest ) doLogRequest(verb, url, body, params, headers, logRequest) clientResponse = requests.delete( url, params = params, headers = headers, json = body, timeout = timeout, **kwargs ) return clientResponse def doLogRequest(verb, url, body, params, headers, logRequest): log.info(resourceInstanceMethod, f'[CLIENT ] {verb} - {url}') if logRequest: log.prettyJson( resourceInstanceMethod, '[CLIENT ] Request', { 'headers': ConverterStatic.getValueOrDefault(headers, dict()), 'query': ConverterStatic.getValueOrDefault(params, dict()), 'body': ConverterStatic.getValueOrDefault(body, dict()) }, condition = True, logLevel = log.INFO ) HTTP_CLIENT_RESOLVERS_MAP = { HttpDomain.Verb.OPTIONS : options, HttpDomain.Verb.GET : get, HttpDomain.Verb.POST : post, HttpDomain.Verb.PUT : put, HttpDomain.Verb.PATCH : patch, HttpDomain.Verb.DELETE : delete } log.wrapper(HttpClientMethod,f'''wrapping {resourceInstanceMethod.__name__}''') def innerResourceInstanceMethod(*args, **kwargs): f'''(*args, {FlaskUtil.KW_HEADERS}={{}}, {FlaskUtil.KW_PARAMETERS}={{}}, **kwargs)''' resourceInstance = args[0] clientResponse = None completeResponse = None try : FlaskManager.validateKwargs( kwargs, resourceInstance, resourceInstanceMethod, requestHeaderClass, requestParamClass ) FlaskManager.validateArgs(args, requestClass, resourceInstanceMethod) clientResponse = None httpClientEvent = getHttpClientEvent(resourceInstanceMethod, *args, **kwargs) if isinstance(httpClientEvent, ManualHttpClientEvent): completeResponse = httpClientEvent.completeResponse elif isinstance(httpClientEvent, HttpClientEvent): try : clientResponse = HTTP_CLIENT_RESOLVERS_MAP.get( httpClientEvent.verb, raiseHttpClientEventNotFoundException )( resourceInstance, *httpClientEvent.args, **httpClientEvent.kwargs ) except Exception as exception: raiseException(clientResponse, exception) raiseExceptionIfNeeded(clientResponse) completeResponse = getCompleteResponse(clientResponse, responseClass, produces) FlaskManager.validateCompleteResponse(responseClass, completeResponse) else: raise Exception('Unknown http client event') except Exception as exception: log.log(innerResourceInstanceMethod, 'Failure at client method execution', exception=exception, muteStackTrace=True) FlaskManager.raiseAndPersistGlobalException(exception, resourceInstance, resourceInstanceMethod, context=HttpDomain.CLIENT_CONTEXT) clientResponseStatus = completeResponse[-1] clientResponseHeaders = completeResponse[1] clientResponseBody = completeResponse[0] if ObjectHelper.isNotNone(completeResponse[0]) else {'message' : HttpStatus.map(clientResponseStatus).enumName} if resourceInstance.logResponse or logResponse : log.prettyJson( resourceInstanceMethod, '[CLIENT ] Response', { 'headers': clientResponseHeaders, 'body': Serializer.getObjectAsDictionary(clientResponseBody), 'status': clientResponseStatus }, condition = True, logLevel = log.INFO ) if returnOnlyBody: return completeResponse[0] else: return completeResponse ReflectionHelper.overrideSignatures(innerResourceInstanceMethod, resourceInstanceMethod) innerResourceInstanceMethod.url = clientMethodConfig.url innerResourceInstanceMethod.headers = clientMethodConfig.headers innerResourceInstanceMethod.requestHeaderClass = clientMethodConfig.requestHeaderClass innerResourceInstanceMethod.requestParamClass = clientMethodConfig.requestParamClass innerResourceInstanceMethod.requestClass = clientMethodConfig.requestClass innerResourceInstanceMethod.responseClass = clientMethodConfig.responseClass innerResourceInstanceMethod.returnOnlyBody = clientMethodConfig.returnOnlyBody innerResourceInstanceMethod.timeout = clientMethodConfig.timeout innerResourceInstanceMethod.propagateAuthorization = clientMethodConfig.propagateAuthorization innerResourceInstanceMethod.propagateApiKey = clientMethodConfig.propagateApiKey innerResourceInstanceMethod.propagateSession = clientMethodConfig.propagateSession innerResourceInstanceMethod.produces = clientMethodConfig.produces innerResourceInstanceMethod.consumes = clientMethodConfig.consumes innerResourceInstanceMethod.logRequest = clientMethodConfig.logRequest innerResourceInstanceMethod.logResponse = clientMethodConfig.logResponse return innerResourceInstanceMethod