swagger 生成代码

  • Post author:
  • Post category:其他


swagger 生成代码

文档:swagger 生成代码.note

链接:http://note.youdao.com/noteshare?id=e1adbff83b6613ef9628381de397e1de&sub=2EB8233C292A41A1841085C002CE131B


添加链接描述

import json_util

# jsonPath=rf"G:\openapi.json"
# jsonPath=rf"G:\file\openapi.json"
jsonPath=rf"H:\download\openapi.json"
# "G:\file\openapi.json"
# "G:\file\openapi.json"
# openapi_gen
# http://10.160.199.103:30412/openapi.json
apiData=json_util.file_path_to_dict(jsonPath)
# D:\proj\python\st-util\apiGe.py
paths=apiData["paths"]
components=apiData["components"]
schemas=components["schemas"]
# http://10.160.199.103:30412/docs#/
def path_to_url(path):
    return f"https://api.tusi.art{path}"

def parsePath(path,info):
    pass
    for method,methodInfo in  info.items():
        print("=========")
        print("path",path)
        # requestBody
        print("method",method)
        # content
        requestBody=methodInfo.get("requestBody",None)
        if requestBody is None:
            continue
        # requestBody=methodInfo['requestBody']
        content=requestBody['content']
        # d["application/json"]["schema"]["$ref"]
        # jsonObj=content["application/json"]
        jsonObj=content.get("application/json",None)
        if jsonObj is None:
            continue
        ref=jsonObj["schema"]["$ref"]
        # /components/schemas/
        refName=ref.replace("#/components/schemas/","")
        schema=schemas[refName]
        print("schema",schema)
        # methodInfo["methodInfo"]=methodInfo
    # return f"https://api.tusi.art{path}"





# for path,info in paths.items():
#     # print(path)
#     parsePath(path,info=info)

api_to_java_class_map={
    "integer":"Integer",
    "string":"String",
    "array":"List<String>",
    "boolean":"Boolean",
}
#  string  msg

# def d(type,):
#     java_class_name=api_to_java_class_map.get(type)

# def d():

from typing import List

def convert_to_list(items) -> List:
    if items is None:
        return None
    if type (items)==str:
        return [items] 
    if items['type'] == 'array':
        return [convert_to_list(item) for item in items['items']]
    else:
        return [items['type']]

def convert_to_list(items) -> List:
    if items is None:
        return None
    if type (items)==str:
        return f"List<{items}>"
    # if items['type'] == 'array':
    if items.get('type') == 'array':
        # return [convert_to_list(item) for item in items['items']]
        # return [convert_to_list(item) for item in items['items']]
        return f"List<{[convert_to_list(item) for item in items['items']]}>"
    else:
        # return [items['type']]
        return [items.get('type')]
    
def propertiesParse(properties):
    # properties
    fieldRowList=[]
    for property,propertyData in properties.items():
        type=propertyData['type']
        
        # {'title': 'ValidationError', 
        # print("type",type)
        # print("property",property)
        java_class_name=api_to_java_class_map.get(type,type)
        fieldRow=f" {java_class_name}  {property}; "
        fieldRowList.append(fieldRow)
        # : {'title': 'History', 'type': 'array', 'items': {'type': 'array', 'items': {'type': 'string'}}
        # 'items': {'type': 'array', 'items': {'type': 'string'} 转化成 List<  List<String > >
        # 'items': {'type': 'string'} 转化成 List<String >
        
        print(fieldRow)
        # print("property",property)
        propertyData=properties[property]
        # print("propertyData",propertyData)
        # items
        items=propertyData.get("items")
        # print("items diaiodhao ",items)
        # items=properties.get("items")
        # print(items)
        items_list=convert_to_list(items)
        # items_type=items.get("type")
        if items_list is not None:
            pass

            # print("items_list ============== ",items_list)
         
        # List<String>
        # type
        if propertyData.get("type",None) is None:
            ref=propertyData["$ref"]
            refName=ref.replace("#/components/schemas/","")
            schema=schemas[refName]
            # print("schema",schema)
            # propertiesParse(schema["properties"])
        else:
            # print("propertyData",propertyData)
            pass
            # pri
    return fieldRowList

# import file_util
# time 
from top.starp.util import time_util
from top.starp.util import file_util

# file_util.

now_time_str=time_util.get_now_time_str()
outputDir=rf"H:\codeGen\swaggerGen/swaggerGen_{now_time_str}"

for schemaName,schemaData in schemas.items():
    print(schemaName)
    print(schemaData)
    # title=schemaData['title']
    # ClassName=title
    ClassName=schemaName
    properties=schemaData['properties']
    fieldRowList=propertiesParse(properties)
    # fieldRowList.join("\n")
    fieldRowsStr="\n".join(fieldRowList)
    # entityCode=f"""
    # {ClassName}
    # {fieldRowsStr}
    # """

    tpl="""
    import lombok.*;

    import java.util.List;

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @ToString
    @Builder
    public class {ClassName} {
        {fieldRowsStr}
    }
    """
    entityCode=tpl.replace("{ClassName}",ClassName).replace("{fieldRowsStr}",fieldRowsStr)
    print(entityCode)
    # file_util. 
    # outputDir=r"G:\file\java\com\tusi\openapi\entity"
    # outputPath=r"G:\file\java\com\tusi\openapi\entity"
    # f"{ClassName}.java"
    
    file_util.write_file(f"{outputDir}/{ClassName}.java",entityCode)
    # with open(outputPath,"w",encoding="utf-8") as f:
    #     f.write(entityCode)

# D:\proj\python\st-util\openapi_gen.py
# python openapi_gen.py



版权声明:本文为jonathan_joestar原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。