Example #1
0
def get_response_imports(definitions: dict):
    imports = []
    for value in definitions.values():
        properties = value.get("properties", {})
        response = properties.get("response", {})
        ref = response.get("$ref")
        if ref:
            imports.append(get_type_from_reference(ref))
            continue
        if response.get("PatternProperties"):
            continue
        for item in [*response.get("properties", {}).values(), response]:
            if item.get("type") == "array":
                ref = item["items"].get("$ref")
                if not ref and item["items"].get("type") == "object":
                    for property_item in item["items"]["properties"].values():
                        property_ref = property_item.get("$ref")
                        if property_ref:
                            imports.append(
                                get_type_from_reference(property_ref))
            else:
                ref = item.get("$ref")
            if ref:
                imports.append(get_type_from_reference(ref))
    return {"vkbottle_types.objects": sorted(set(imports))}
Example #2
0
def jsonschema_object_factory(classname: str, json_properties: dict) -> 'Model':
    schema_type = json_properties['response'].get('type', '$ref')

    if schema_type == '$ref':
        t = get_type_from_reference(json_properties['response']['$ref'])
        t = Annotation.type_string_to_default_type(t)
        return SingleTypeModel(classname, f'Optional[{t}]')
    elif schema_type == 'integer':
        return SingleTypeModel(classname, 'int')
    elif schema_type == 'boolean':
        return SingleTypeModel(classname, 'bool')
    elif schema_type == 'array':
        type_ = None
        if json_properties['response']['items'].get('type'):
            type_ = json_properties['response']['items']['type']

            type_ = Annotation('Array', list_inner_type=type_)
        else:
            type_ = json_properties['response']['items']['$ref']
            type_ = get_type_from_reference(type_)

        return SingleTypeModel(classname, f'List[{type_}]')
    elif schema_type == 'string':
        return SingleTypeModel(classname, 'string')
    else:
        # HARDCODED THIS IS UNIQUE CASE
        if json_properties['response'].get('patternProperties'):
            return SingleTypeModel(classname, 'typing.Dict[str, int]')

        properties = json_properties['response']['properties']
        names = {name: None for name in properties.keys()}
        json_properties = {name: None for name in names}
        types = []
        for _, value in properties.items():
            if value.get('type'):
                property_type = value.get('type')
                if property_type == 'array':
                    ref_type = value['items'].get('$ref')
                    if ref_type:
                        types.append([get_type_from_reference(ref_type)])
                    else:
                        types.append([value['items']['type']])
                else:
                    types.append(value['type'])
            else:
                t = get_type_from_reference(value['$ref'])
                types.append(t)
        return ResponseModel(classname, types, **json_properties)
Example #3
0
def jsonschema_object_factory(classname: str, json_properties: dict):
    schema_type = json_properties["response"].get("type", "$ref")

    if schema_type == "array":
        type_ = json_properties["response"]["items"].get("type")
        if type_ == "object":
            properties = json_properties["response"]["items"]["properties"]
            return ResponseModel(classname, get_types(properties),
                                 **properties)
        return ""
    elif (schema_type in [
            "$ref",
            "integer",
            "number",
            "string",
            "boolean",
    ] or json_properties["response"].get("patternProperties")):
        return ""
    superclass = "BaseResponse"
    all_of = json_properties["response"].get("allOf")
    if all_of:
        for item in all_of:
            ref = item.get("$ref")
            if ref:
                superclass = get_type_from_reference(ref)
                continue
            properties = item["properties"]
    else:
        properties = json_properties["response"]["properties"]
    names = {name: None for name in properties.keys()}
    json_properties = {name: None for name in names}
    types = get_types(properties)
    return ResponseModel(classname, types, superclass, **json_properties)
Example #4
0
def write_response_alias(schema_body: dict) -> None:
    text = ""
    annotations = {}
    for classname, value in schema_body.items():
        schema_type = value["properties"]["response"].get("type", "$ref")
        if schema_type == "$ref":
            annotation = convert_to_python_type(
                get_type_from_reference(
                    value["properties"]["response"]["$ref"]))
        elif schema_type == "array":
            type_ = value["properties"]["response"]["items"].get("type")
            if not type_:
                type_ = value["properties"]["response"]["items"]["$ref"]
                annotation = f'typing.List["{get_type_from_reference(type_)}"]'
            elif type_ == "object":
                annotation = f'typing.List["{classname}Model"]'
            else:
                annotation = f"typing.List[{convert_to_python_type(type_)}]"
        # HARDCODED THIS IS UNIQUE CASE
        elif value["properties"]["response"].get("patternProperties"):
            annotation = "typing.Dict[str, int]"
        elif schema_type == "object":
            annotation = f'"{classname}Model"'
        else:
            annotation = convert_to_python_type(schema_type)
        annotations[classname] = annotation
        properties = {"response: " + annotation: None}
        text += str(ResponseModel(classname, **properties))
    return text, annotations
    def __init__(self, classname, prepared_dict):
        self.class_form: ClassForm = ClassForm(classname)
        super_classes_list = []

        for element in prepared_dict[classname]["allOf"]:
            properties = element.get("properties")
            required = prepared_dict[classname].get("required", [])
            reference = element.get("$ref")

            if properties:
                for name in sorted(properties.keys()):
                    type_anno = get_annotation_type(properties[name])

                    text = properties[name].get("description")
                    self.class_form.add_param(
                        name,
                        None,
                        type=properties[name].get("type"),
                        annotation=type_anno,
                        required=name in required,
                    )
                    self.class_form.add_description_row(name, text)
            if reference:
                ref = get_type_from_reference(reference)
                super_classes_list.append(ref)
        if super_classes_list:
            formatted = ", ".join(super_classes_list)
            if len(formatted) >= 80:
                formatted = "\n\t" + formatted.replace(", ", ",\n\t") + "\n"
            self.class_form.set_super_class(formatted)
def schema_object_fabric_method(classname, prepared_dict):
    json_type = prepared_dict[classname]
    if json_type.get("type") == "object":
        if json_type.get("allOf"):
            return SchemaAllOfObject(classname, prepared_dict)
        elif json_type.get("properties"):
            return SchemaObject(classname, prepared_dict)
        elif json_type.get("oneOf"):
            return SchemaOneOfObject(classname, prepared_dict)

    elif json_type.get("type") == "string":
        # if enum is numerical
        if not json_type.get("enum"):
            return SchemaUndefined(classname)
        elif isinstance(json_type["enum"][0], int):
            return SchemaEnumInitialized(classname, prepared_dict)
        else:
            return SchemaEnum(classname, prepared_dict)

    elif json_type.get("type") == "integer":
        return SchemaEnumInitialized(classname, prepared_dict)

    elif json_type.get("type") == "boolean":
        return SchemaBoolean(classname, prepared_dict)

    elif json_type.get("type") == "array":
        return SchemaArray(classname, prepared_dict)

    elif json_type.get("$ref"):
        predecessor = get_type_from_reference(json_type["$ref"])
        return SchemaReference(classname, prepared_dict, predecessor)

    elif json_type.get("type") is None:
        return SchemaUndefined(classname)
Example #7
0
def get_types(properties: dict):
    types = []
    for value in properties.values():
        property_type = value.get("type")
        if not property_type:
            t = get_type_from_reference(value["$ref"])
            types.append(t)
            continue
        elif property_type == "array":
            ref_type = value["items"].get("$ref")
            if not ref_type:
                types.append([value["items"]["type"]])
                continue
            types.append([get_type_from_reference(ref_type)])
        else:
            types.append(value["type"])
    return types
Example #8
0
def get_references(item: dict):
    references = []
    all_of = item.get("allOf", [])
    one_of = item.get("oneOf", [])
    for i in [*all_of, *one_of, item]:
        reference = i.get("$ref")
        if reference:
            references.append(get_type_from_reference(reference, False))
    return references
    def __init__(self, classname, prepared_dict):
        self.class_form: ClassForm = ClassForm(classname)
        for name in prepared_dict[classname]['properties'].keys():
            properties = prepared_dict[classname]['properties']

            if properties[name].get('type') == 'array':
                if properties[name]['items'].get('type'):
                    type_anno = [properties[name]['items']['type']]
                else:
                    type_anno = properties[name]['items'].get('$ref')
                    type_anno = [get_type_from_reference(type_anno)]
            elif properties[name].get('type'):
                type_anno = properties[name].get('type')
            else:
                type_anno = properties[name].get('$ref')
                type_anno = get_type_from_reference(type_anno)

            text = properties[name].get('description')
            self.class_form.add_param(name, None, annotation=type_anno)
            self.class_form.add_description_row(name, text)
Example #10
0
    def __str__(self):
        items = self.params["items"]
        param_type = self.params["type"]
        param_annotate = convert_to_python_type(self.params['annotate'])

        if param_annotate == 'list' and items.get("$ref", items.get("type")):
            post_annotate = (get_type_from_reference(items["$ref"])
                             if items.get("$ref") else items["type"])
            param_annotate = "List[%s]" % convert_to_python_type(post_annotate)

        if param_type is False:
            return f"Optional[{param_annotate}] = None"
        return param_annotate
    def __init__(self, classname, prepared_dict):
        self.class_form: ClassForm = ClassForm(classname)
        super_classes_list = []

        for element in prepared_dict[classname]['allOf']:
            properties = element.get('properties')
            reference = element.get('$ref')

            if properties:
                for name in properties.keys():
                    text = properties[name].get('description')
                    self.class_form.add_param(name, None)
                    self.class_form.add_description_row(name, text)
            if reference:
                ref = get_type_from_reference(reference)
                super_classes_list.append(ref)

        self.class_form.set_super_class(",\n\t".join(super_classes_list))
    def __init__(self, classname, prepared_dict):
        one_of = prepared_dict[classname]["oneOf"]
        references = [element.get("$ref") for element in one_of]
        if all(references):
            self.class_form: ClassForm = ClassForm(classname)
            super_classes_list = []

            for reference in references:
                ref = get_type_from_reference(reference)
                super_classes_list.append(ref)
            if super_classes_list:
                formatted = ", ".join(super_classes_list)
                if len(formatted) >= 80:
                    formatted = "\n\t" + formatted.replace(", ",
                                                           ",\n\t") + "\n"
                self.class_form.set_super_class(formatted)
        else:
            types = ", ".join(
                convert_to_python_type(item["type"]) for item in one_of)
            self.class_form = f"\n\n{classname} = typing.Union[{types}]\n"
Example #13
0
def test_get_type_from_reference(test_input, expected):
    assert get_type_from_reference(test_input) == expected