예제 #1
0
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
    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 = ReflectionHelper.getAttributeNameList(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.warning(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)
예제 #2
0
def serializeIt(fromJson, toClass, fatherClass=None) :
    # print(f'fromJson: {fromJson}, toClass: {toClass}, fatherClass: {fatherClass}')
    if ObjectHelper.isDictionary(fromJson) and ObjectHelper.isDictionaryClass(toClass) :
        # objectInstance = {}
        # for key, value in fromJson.items() :
        #     innerToClass = getTargetClassFromFatherClassAndChildMethodName(fatherClass, key)
        #     objectInstance[key] = serializeIt(fromJson, innerToClass, fatherClass=fatherClass)
        # return objectInstance
        return fromJson
    # print()
    # print()
    # print(fromJson)
    # print(f'fromJson: {fromJson}')
    # print(f'toClass: {toClass}')
    if ObjectHelper.isNativeClassInstance(fromJson) and toClass == fromJson.__class__ :
        return fromJson
    attributeNameList = ReflectionHelper.getAttributeNameList(toClass)
    classRole = getClassRole(toClass)
    # print(f'        classRole = {classRole}')
    # print(f'        attributeNameList = {attributeNameList}')
    fromJsonToDictionary = {}
    for attributeName in attributeNameList :
        # print(f'        fromJson.get({attributeName}) = {fromJson.get(attributeName)}')
        jsonAttributeValue = fromJson.get(attributeName)
        if ObjectHelper.isNone(jsonAttributeValue) :
            jsonAttributeValue = fromJson.get(f'{attributeName[0].upper()}{attributeName[1:].lower()}')
        if ObjectHelper.isNotNone(jsonAttributeValue) :
            # print(f'jsonAttributeValue: {jsonAttributeValue}')
            fromJsonToDictionary[attributeName] = resolveValue(jsonAttributeValue, attributeName, classRole, fatherClass=fatherClass)
            # logList = [
            #     f'jsonAttributeValue: {jsonAttributeValue}',
            #     f'attributeName: {attributeName}',
            #     f'classRole: {classRole}',
            #     f'fromJsonToDictionary: {fromJsonToDictionary}',
            #     f'toClass: {toClass}'
            # ]
            # log.prettyPython(serializeIt, 'logList', logList, logLevel=log.DEBUG)
        else :
            fromJsonToDictionary[attributeName] = jsonAttributeValue
        # if jsonAttributeValue :
        #     ReflectionHelper.setAttributeOrMethod(fromObject, attributeName, jsonAttributeValue)
    args = []
    kwargs = fromJsonToDictionary.copy()
    # print(f'fromJsonToDictionary = {fromJsonToDictionary}')
    objectInstance = None
    for key,value in fromJsonToDictionary.items() :
        # print(f'*args{args},**kwargs{kwargs}')
        try :
            objectInstance = toClass(*args,**kwargs)
            break
        except :
            args.append(value)
            del kwargs[key]
        # print(f'args = {args}, kwargs = {kwargs}')
    # print(f'args = {args}, kwargs = {kwargs}')
    if ObjectHelper.isNone(objectInstance) :
        raise Exception(f'Not possible to instanciate {ReflectionHelper.getName(toClass, muteLogs=True)} class')
    # print(objectInstance)
    # print()
    # print()
    # if objectInstance is [] :
    #     print(fromJson, toClass, fatherClass)
    return objectInstance
예제 #3
0
def getAttributeNameList_andPleaseSomeoneSlapTheFaceOfTheGuyWhoDidItInSqlAlchemy(instanceClass):
    attributeNameList = ReflectionHelper.getAttributeNameList(instanceClass)
    return attributeNameList if not isModelClass(instanceClass) else [attributeName for attributeName in attributeNameList if not SQL_ALCHEMY_RESGITRY_PUBLIC_REFLECTED_ATTRIBUTE_PRETTY_MUCH_THE_WORST_CODE_I_SAW_IN_MY_LIFE == attributeName]
예제 #4
0
def addDtoToUrlVerb(verb,
                    url,
                    dtoClass,
                    documentation,
                    dtoType=v.OBJECT,
                    where=None):
    log.log(
        addDtoToUrlVerb,
        f'verb: {verb}, url: {url}, dtoClass: {dtoClass}, dtoType: {dtoType}, where: {where}'
    )
    if dtoClass:
        if not isinstance(dtoClass, list):
            if not c.TYPE_DICT == ReflectionHelper.getName(dtoClass,
                                                           muteLogs=True):
                dtoName = getDtoDocumentationName(dtoClass)
                if KW_REQUEST == where:
                    documentation[k.PATHS][url][verb][k.PARAMETERS].append({
                        k.NAME:
                        v.BODY,
                        k.TYPE:
                        v.OBJECT,
                        k.IN:
                        v.BODY,
                        k.REQUIRED:
                        True,
                        k.DESCRIPTION:
                        None,
                        k.SCHEMA:
                        getDtoSchema(dtoName, dtoType, dtoClass)
                    })
                elif KW_RESPONSE == where:
                    documentation[k.PATHS][url][verb][k.RESPONSES][
                        k.DEFAULT_STATUS_CODE] = {
                            k.DESCRIPTION: v.DEFAULT_RESPONSE,
                            k.SCHEMA: getDtoSchema(dtoName, dtoType, dtoClass)
                        }
                if not dtoName in documentation[k.DEFINITIONS]:
                    dtoClassDoc = {}
                    documentation[k.DEFINITIONS][dtoName] = dtoClassDoc
                    dtoClassDoc[k.TYPE] = v.OBJECT
                    dtoClassDoc[k.PROPERTIES] = {}
                    dtoClassDoc[
                        k.REQUIRED] = ReflectionHelper.getAttributeNameList(
                            dtoClass)
                    for attributeName in dtoClassDoc[k.REQUIRED]:
                        attributeType = getTypeFromAttributeNameAndChildDtoClass(
                            attributeName, dtoType)
                        childDtoClass = getNullableChildDtoClass(
                            attributeName, dtoClass, verb, url, documentation)
                        if childDtoClass:
                            dtoClassDoc[
                                k.PROPERTIES][attributeName] = getDtoSchema(
                                    attributeName, attributeType,
                                    childDtoClass)
                        else:
                            dtoClassDoc[k.PROPERTIES][attributeName] = {
                                k.TYPE: attributeType,
                                k.EXAMPLE: None
                            }
            else:
                dtoName = getDtoDocumentationName(dtoClass)
                if KW_REQUEST == where:
                    documentation[k.PATHS][url][verb][k.PARAMETERS].append({
                        k.NAME:
                        v.BODY,
                        k.TYPE:
                        v.OBJECT,
                        k.IN:
                        v.BODY,
                        k.REQUIRED:
                        True,
                        k.DESCRIPTION:
                        None,
                        k.SCHEMA:
                        getDtoSchema(dtoName, dtoType, dtoClass)
                    })
                elif KW_RESPONSE == where:
                    documentation[k.PATHS][url][verb][k.RESPONSES][
                        k.DEFAULT_STATUS_CODE] = {
                            k.DESCRIPTION: v.DEFAULT_RESPONSE,
                            k.SCHEMA: getDtoSchema(dtoName, dtoType, dtoClass)
                        }
                if not dtoName in documentation[k.DEFINITIONS]:
                    dtoClassDoc = {}
                    documentation[k.DEFINITIONS][dtoName] = dtoClassDoc
                    dtoClassDoc[k.TYPE] = v.OBJECT
                    dtoClassDoc[k.PROPERTIES] = {}
                    dtoClassDoc[k.REQUIRED] = []

        elif 1 == len(dtoClass):
            if dtoClass[0] and not isinstance(dtoClass[0], list):
                addDtoToUrlVerb(verb,
                                url,
                                dtoClass[0],
                                documentation,
                                where=where)
            elif 1 == len(dtoClass[0]):
                if dtoClass[0][0] and not isinstance(dtoClass[0][0], list):
                    addDtoToUrlVerb(verb,
                                    url,
                                    dtoClass[0][0],
                                    documentation,
                                    dtoType=v.ARRAY,
                                    where=where)
예제 #5
0
 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})'
                 )