Example #1
0
 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
Example #2
0
 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)
Example #3
0
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 getErrorMessage(clientResponse, exception=None):
    completeErrorMessage = f'{HttpClientConstant.ERROR_AT_CLIENT_CALL_MESSAGE}{c.DOT_SPACE}{HttpClientConstant.CLIENT_DID_NOT_SENT_ANY_MESSAGE}'
    errorMessage = HttpClientConstant.CLIENT_DID_NOT_SENT_ANY_MESSAGE
    possibleErrorMessage = None
    bodyAsJson = {}
    try :
        bodyAsJson = clientResponse.json()
    except Exception as innerException :
        bodyAsJsonException = FlaskUtil.safellyGetResponseJson(clientResponse)
        log.log(getErrorMessage, f'Invalid client response: {bodyAsJsonException}', exception=innerException)
        log.debug(getErrorMessage, f'Not possible to get error message from client response: {bodyAsJsonException}. Proceeding with value {bodyAsJson} by default', exception=innerException, muteStackTrace=True)
    try:
        if ObjectHelper.isNotNone(clientResponse):
            if ObjectHelper.isDictionary(bodyAsJson):
                possibleErrorMessage = bodyAsJson.get('message', bodyAsJson.get('error')).strip()
            if ObjectHelper.isList(bodyAsJson) and 0 < len(bodyAsJson):
                possibleErrorMessage = bodyAsJson[0].get('message', bodyAsJson[0].get('error')).strip()
        if ObjectHelper.isNotNone(possibleErrorMessage) and StringHelper.isNotBlank(possibleErrorMessage):
            errorMessage = f'{c.LOG_CAUSE}{possibleErrorMessage}'
        else:
            log.debug(getErrorMessage, f'Client response {FlaskUtil.safellyGetResponseJson(clientResponse)}')
        exceptionPortion = HttpClientConstant.ERROR_AT_CLIENT_CALL_MESSAGE if ObjectHelper.isNone(exception) or StringHelper.isBlank(exception) else str(exception)
        completeErrorMessage = f'{exceptionPortion}{c.DOT_SPACE}{errorMessage}'
    except Exception as exception:
        log.warning(getErrorMessage, f'Not possible to get error message. Returning {completeErrorMessage} by default', exception=exception)
    return completeErrorMessage
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 __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
Example #7
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
Example #8
0
def mustRun_withSuccess_ExecutingActionFirst():
    # Arrange
    def myAction(c, d=None):
        return c + d

    def myFunction(a):
        return a

    returns = {}

    @Test(callBefore=myAction,
          argsOfCallBefore='f',
          kwargsOfCallBefore={'d': 'g'},
          returns=returns,
          environmentVariables={
              SettingHelper.ACTIVE_ENVIRONMENT: None,
              **MUTED_LOG_HELPER_SETTINGS
          })
    def myTest():
        assert 'a' == myFunction('a')

    exception = None

    # Act
    try:
        myTest()
    except Exception as e:
        exception = e

    # Assert
    assert ObjectHelper.isNone(exception)
    assert 'fg' == returns['returnOfCallBefore']
Example #9
0
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)
Example #10
0
def apiKeyManager_worksProperly():
    # arrange
    SECRET = 'abcd'
    SESSION_DURATION = 10 + 360
    ALGORITHM = 'HS256'
    HEADER_NAME = 'Context'
    HEADER_TYPE = 'ApiKey '
    IDENTITY = RandomHelper.string(minimum=100, maximum=150)
    CONTEXT = 'ABCD'
    CONTEXT_LIST = [CONTEXT]
    DATA = {'personal': 'data'}
    deltaMinutes = DateTimeHelper.timeDelta(minutes=SESSION_DURATION)
    apiKeyManager = ApiKeyManager.JwtManager(SECRET, ALGORITHM, HEADER_NAME,
                                             HEADER_TYPE)
    timeNow = DateTimeHelper.dateTimeNow()
    payload = {
        JwtConstant.KW_IAT: timeNow,
        JwtConstant.KW_NFB: timeNow,
        JwtConstant.KW_JTI:
        f"{int(f'{time.time()}'.replace('.', ''))+int(f'{time.time()}'.replace('.', ''))}",
        JwtConstant.KW_EXPIRATION: timeNow + deltaMinutes,
        JwtConstant.KW_IDENTITY: IDENTITY,
        JwtConstant.KW_FRESH: False,
        JwtConstant.KW_TYPE: JwtConstant.ACCESS_VALUE_TYPE,
        JwtConstant.KW_CLAIMS: {
            JwtConstant.KW_CONTEXT: CONTEXT_LIST,
            JwtConstant.KW_DATA: DATA
        }
    }

    # act
    totalRuns = 10000
    lines = 3
    initTime = time.time()
    for i in range(totalRuns):
        encodedPayload = apiKeyManager.encode(payload)
        decodedPayload = apiKeyManager.decode(encodedPayload)
        accessException = TestHelper.getRaisedException(
            apiKeyManager.validateAccessApiKey, rawJwt=decodedPayload)
    refreshException = TestHelper.getRaisedException(
        apiKeyManager.validateRefreshApiKey, rawJwt=decodedPayload)
    endTime = time.time() - initTime

    # assert
    assert lines * .0001 > endTime / totalRuns, (lines * .0001,
                                                 endTime / totalRuns)
    assert ObjectHelper.equals(payload,
                               decodedPayload), (payload, decodedPayload)
    assert ObjectHelper.isNone(accessException), accessException
    assert ObjectHelper.isNotNone(refreshException), refreshException
    assert ObjectHelper.equals(
        GlobalException.__name__,
        type(refreshException).__name__), (GlobalException.__name__,
                                           type(refreshException).__name__,
                                           refreshException)
    assert ObjectHelper.equals(401, refreshException.status)
    assert ObjectHelper.equals('Invalid apiKey', refreshException.message)
    assert ObjectHelper.equals(
        'Refresh apiKey should have type refresh, but it is access',
        refreshException.logMessage)
Example #11
0
def Function_withSuccess():
    # Arrange
    TEST = RandomHelper.string(minimum=10)

    @Function
    def myFunction(something):
        return TEST, something

    @Function
    def myOtherFunction(something):
        raise Exception(TEST)

    SOMETHING = RandomHelper.string(minimum=10)
    exception = None

    # Act
    myRestult = myFunction(SOMETHING)
    myOtherResult = None
    try:
        myOtherResult = myOtherFunction(SOMETHING)
    except Exception as ext:
        exception = ext

    # Assert
    assert (TEST, SOMETHING) == myRestult
    assert ObjectHelper.isNone(myOtherResult)
    assert ObjectHelper.isNotNone(exception)
    assert TEST == str(exception)
Example #12
0
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
Example #13
0
def patchAccessToken(newContextList=None,
                     headers=None,
                     data=None,
                     rawJwt=None,
                     apiInstance=None):
    headers = headers if ObjectHelper.isNone(rawJwt) else {
        **getJwtHeaders(),
        **ConverterStatic.getValueOrDefault(headers, dict())
    }
    rawJwt = getJwtBody(rawJwt=rawJwt, apiInstance=apiInstance)
    deltaMinutes = UtcDateTimeUtil.ofTimestamp(
        getExpiration(rawJwt=rawJwt)) - UtcDateTimeUtil.now()
    userClaims = {
        JwtConstant.KW_CONTEXT:
        list(
            set([
                *safellyGetContext(getContext(rawJwt=rawJwt)),
                *safellyGetContext(newContextList)
            ])),
        JwtConstant.KW_DATA: {
            **safellyGetData(getData(rawJwt=rawJwt)),
            **safellyGetData(data)
        }
    }
    addAccessTokenToBlackList(rawJwt=rawJwt, apiInstance=apiInstance)
    return create_access_token(identity=getIdentity(rawJwt=rawJwt),
                               user_claims=userClaims,
                               fresh=False,
                               expires_delta=deltaMinutes,
                               headers=ConverterStatic.getValueOrDefault(
                                   headers, dict()))
def getCompleteResponse(clientResponse, responseClass, produces, fallbackStatus=HttpStatus.INTERNAL_SERVER_ERROR):
    responseBody, responseHeaders, responseStatus = dict(), dict(), fallbackStatus
    responseHeaders = FlaskUtil.safellyGetResponseHeaders(clientResponse)
    responseBody = FlaskUtil.safellyGetResponseJson(clientResponse)
    try :
        responseStatus = HttpStatus.map(HttpStatus.NOT_FOUND if ObjectHelper.isNone(clientResponse.status_code) else clientResponse.status_code)
    except Exception as exception :
        responseStatus = HttpStatus.map(fallbackStatus)
        log.warning(getCompleteResponse, f'Not possible to get client response status. Returning {responseStatus} by default', exception=exception)
    responseHeaders = {
        **{HttpDomain.HeaderKey.CONTENT_TYPE: produces},
        **responseHeaders
    }
    responseStatus = ConverterStatic.getValueOrDefault(responseStatus, HttpStatus.map(fallbackStatus))
    if ObjectHelper.isNone(responseClass):
        return responseBody, responseHeaders, responseStatus
    return Serializer.convertFromJsonToObject(responseBody, responseClass), responseHeaders, responseStatus
Example #15
0
 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
Example #16
0
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 __eq__(self, other) :
     if ObjectHelper.isNone(other) :
         return self is None
     isEqual = True
     for value, name in ReflectionHelper.getAttributeDataList(other) :
         attributeIsEqual = ReflectionHelper.getAttributeOrMethod(self, name) == ReflectionHelper.getAttributeOrMethod(other, name)
         isEqual = isEqual == attributeIsEqual and True == attributeIsEqual
     return isEqual
def isModel(thing):
    if ObjectHelper.isNone(thing):
        return False
    return (
        isinstance(thing, DeclarativeMeta) or isModelClass(thing.__class__) or (
            isSerializerCollection(thing) and len(thing) > 0 and isModel(thing[0]) if ObjectHelper.isNotDictionary(thing) else isModel(thing.values()[0])
        )
    )
Example #19
0
def isApiInstance(apiInstance):
    if ObjectHelper.isNone(apiInstance):
        return False
    apiClassName = flask_restful.Api.__name__
    moduleName = flask_restful.__name__
    return apiClassName == getClassName(
        apiInstance) and apiClassName == getQualitativeName(
            apiInstance) and moduleName == getModuleName(apiInstance)
Example #20
0
def Method_withSuccess():
    # Arrange
    TEST = RandomHelper.string(minimum=10)

    class MyClass:
        @Method
        def myMethod(self, something):
            return TEST, something

        @Method
        def myOtherMethod(self, something):
            raise Exception(TEST)

    @Method
    def myNotMethod(self, something):
        raise Exception(TEST)

    SOMETHING = RandomHelper.string(minimum=10)
    methodException = None
    notMethodEception = None
    myClass = MyClass()

    # Act
    myRestult = myClass.myMethod(SOMETHING)
    myOtherResult = None
    try:
        myOtherResult = myClass.myOtherMethod(SOMETHING)
    except Exception as ext:
        methodException = ext
    myNotMethodResult = None
    try:
        myNotMethodResult = myNotMethod(None, SOMETHING)
    except Exception as ext:
        notMethodEception = ext
        # print(notMethodEception)

    # Assert
    assert (TEST, SOMETHING) == myRestult
    assert ObjectHelper.isNone(myOtherResult)
    assert ObjectHelper.isNotNone(methodException)
    assert TEST == str(methodException)
    assert ObjectHelper.isNone(myNotMethodResult)
    assert ObjectHelper.isNotNone(notMethodEception)
    assert TEST == str(notMethodEception)
Example #21
0
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 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)
Example #23
0
 def getStaticPackagePath(self):
     staticPackage = self.getSetting(AttributeKey.PYTHON_STATIC_PACKAGE)
     self.log(f'User static package: "{site.getusersitepackages()}"')
     self.log(
         f'Static package list: {StringHelper.prettyJson(site.getsitepackages())}'
     )
     self.log(
         f'Static package (taken from application.yml): "{staticPackage}"')
     if ObjectHelper.isNone(staticPackage):
         staticPackage = str(self.STATIC_PACKAGE_PATH)
     self.setting(f'Static package: "{staticPackage}"')
     return staticPackage
def runApi(*args, api=None, **kwargs):
    if ObjectHelper.isNone(api):
        api = getApi()
    muteLogs(api.app)
    if 'host' not in kwargs and api.host:
        kwargs['host'] = api.host
    if 'port' not in kwargs and api.port:
        kwargs['port'] = api.port
    apiUrl = getApiUrl(api)
    log.success(runApi, f'Api will run at {apiUrl}')
    log.success(runApi, f'Documentation will be available at {apiUrl}/swagger')
    api.app.run(*args, **kwargs)
Example #25
0
 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
Example #26
0
def retrieveApiInstance(apiInstance=None, arguments=None):
    if isApiInstance(apiInstance):
        return apiInstance
    if isApiInstance(API_INSTANCE_HOLDER.get(KEY_API_INSTANCE)):
        return API_INSTANCE_HOLDER.get(KEY_API_INSTANCE)
    if ObjectHelper.isNone(apiInstance) and ObjectHelper.isNotNone(arguments):
        try:
            apiInstance = arguments[0].globals.api
        except Exception as exception:
            log.warning(
                retrieveApiInstance,
                f'''Not possible to retrieve api instance by {arguments}. Going for another approach''',
                exception=exception)
    if not isApiInstance(apiInstance):
        log.warning(
            retrieveApiInstance,
            f'''Not possible to retrieve api instance. Going for a slower approach'''
        )
        apiInstance = getNullableApi()
    if ObjectHelper.isNone(apiInstance):
        raise Exception('Not possible to retrieve api instance')
    API_INSTANCE_HOLDER[KEY_API_INSTANCE] = apiInstance
    return apiInstance
def initialize(apiInstance,
               defaultUrl=None,
               openInBrowser=False,
               filePath=None,
               successStatus=False,
               settingStatus=False,
               debugStatus=False,
               warningStatus=False,
               wrapperStatus=False,
               failureStatus=False,
               errorStatus=False,
               testStatus=False,
               logStatus=False):
    if ObjectHelper.isNone(apiInstance):
        globalsInstance = runGlobals(filePath,
                                     successStatus=successStatus,
                                     settingStatus=settingStatus,
                                     debugStatus=debugStatus,
                                     warningStatus=warningStatus,
                                     wrapperStatus=wrapperStatus,
                                     failureStatus=failureStatus,
                                     errorStatus=errorStatus,
                                     testStatus=testStatus,
                                     logStatus=logStatus)
    defaultUrl
    openInBrowser
    url = getApiUrl(apiInstance)
    if defaultUrl:
        url = f'{url}{defaultUrl}'

    def inBetweenFunction(function, *argument, **keywordArgument):
        log.debug(initialize, f'''{function.__name__} method''')
        if (openInBrowser):
            log.debug(initialize, f'''Openning "{url}" url in rowser''')
            # WebBrowser.openUrlInChrome(url)
            WebBrowser.openUrl(url)

        def innerFunction(*args, **kwargs):
            try:
                functionReturn = function(*args, **kwargs)
            except Exception as exception:
                raise Exception(
                    f'Failed to initialize. Cause: {str(exception)}')
            return functionReturn

        return innerFunction

    return inBetweenFunction
Example #28
0
def mustLogPretyPythonWithoutColors():
    # Arrange
    dictionaryInstance = {**{}, **DICTIONARY_INSTANCE}
    exception = None

    # Act
    try:
        log.prettyPython(mustLogPretyPythonWithoutColors,
                         'prettyPythonWithoutColors', dictionaryInstance)
    except Exception as e:
        log.failure(mustLogPretyPythonWithoutColors,
                    'Failed to log prety python in this method call', e)
        exception = e

    # Assert
    assert ObjectHelper.isNone(exception)
Example #29
0
def convertFromJsonToObject(fromJson, toClass, fatherClass=None) :
    if ObjectHelper.isNone(fatherClass) :
        fatherClass = toClass
    # print(f'isSerializerList(toClass): {isSerializerList(toClass)}')
    if isSerializerList(toClass) :
        for innerToObjectClass in toClass :
            if isSerializerList(innerToObjectClass) :
                objectList = []
                for fromJsonElement in fromJson :
                    objectList.append(convertFromJsonToObject(fromJsonElement, innerToObjectClass[0], fatherClass=fatherClass))
                # print(f'convertFromJsonToObject: {objectList}')
                return objectList
            else :
                return convertFromJsonToObject(fromJson, innerToObjectClass, fatherClass=fatherClass)
    else :
        return serializeIt(fromJson, toClass, fatherClass=fatherClass)
Example #30
0
def muteLogs(api):
    import logging
    from werkzeug.serving import WSGIRequestHandler
    werkzeug_logger = logging.getLogger('werkzeug')
    werkzeug_logger.disabled = True
    api.app.logger.disabled = True
    apschedulerLoggerEnabled = api.globals.getApiSetting(
        ConfigurationKeyConstant.API_SCHEDULER_ENABLE)
    apscheduler_logger = logging.getLogger('apscheduler.scheduler')
    default_apscheduler_logger = logging.getLogger(
        'apscheduler.executors.default')
    apscheduler_logger.disabled = True if ObjectHelper.isNone(
        apschedulerLoggerEnabled) else not apschedulerLoggerEnabled
    apscheduler_logger.propagate = not apscheduler_logger.disabled
    default_apscheduler_logger.disabled = apscheduler_logger.disabled
    default_apscheduler_logger.propagate = not apscheduler_logger.disabled
    WSGIRequestHandler.log = lambda self, type, message, *args: None  ###- getattr(werkzeug_logger, type)('%s %s' % (self.address_string(), message % args))