python處理apiDoc轉swagger

来源:https://www.cnblogs.com/baby7/archive/2023/02/01/python_apidoc_to_swagger.html
-Advertisement-
Play Games

使用apidoc包生成apidoc的json格式數據,然後使用python讀取出介面地址、名字、組名、輸入參數格式和例子、輸出參數格式和例子等,然後根據swagger格式填入對應的數據即可生成swagger的json格式 ...


python處理apiDoc轉swagger

需要轉換的介面

現在我需要轉換的介面全是nodejs寫的數據,而且均為post傳輸的json格式介面

apiDoc格式

apiDoc代碼中的格式如下:

/**
 * @api {方法} 路徑 標題
 * @apiGroup Group
 * @apiDescription 描述這個API的信息
 *
 * @apiParam {String} userName 用戶名
 * @apiParamExample {json} request-example
 * {
 *  "userName": "Eve"
 * }
 *
 * @apiError {String} message 錯誤信息
 * @apiErrorExample  {json} error-example
 * {
 *   "message": "用戶名不存在"
 * }
 * 
 * 
 * @apiSuccess {String} userName 用戶名
 * @apiSuccess {String} createTime 創建時間
 * @apiSuccess {String} updateTime 更新時間
 * @apiSuccessExample  {json} success-example
 * {
 *   "userName": "Eve",
 *   "createTime": "1568901681"
 *   "updateTime": "1568901681"
 * }
 */function getUserInfo(username) {
  // 假如這個函數是根據用戶名返回用戶信息的
}

使用npm安裝apidoc插件:

npm install apidoc

再新建對應的apidoc.json,格式如下:

{
  "name": "文檔名",
  "version": "版本號",
  "description": "解釋",
  "title": "標題",
  "url" : "地址"
}

然後在apidoc.json路徑下執行命令可以生成介面文檔(src是介面代碼文件夾,apidoc是生成文檔的文件夾):

apidoc -i src/ -o apidoc/

生成後可以在apidoc文件夾中打開index.html查看生成的介面文檔,生成文檔時會生成一個api_data.json,下麵會用到

swagger格式

這裡我們暫時只需要關註參數為json的介面格式

{
    "swagger": "2.0",
    "info": {
        "description": "1.0版本介面文檔",
        "version": "1.0.5",
        "title": "智能醫療輔助平臺",
        "termsOfService": "http://swagger.io/terms/"
    },
    "host": "http://localhost:8080",
    "basePath": "/",
    "tags": [],
    "paths": {},
    "definitions": {}
}

其中path是存放介面的,tags是存放的分組名列表,definitions是實體列表(json參數)

思路

使用apidoc包生成apidoc的json格式數據,然後使用python讀取出介面地址、名字、組名、輸入參數格式和例子、輸出參數格式和例子等,然後根據swagger格式填入對應的數據即可生成swagger的json格式
我的話是會直接使用處理出的swagger的json格式的數據導入yApi中

代碼

代碼雖然在下麵,但是是我臨時著急用寫的,有的地方是寫死的,需要改,這裡放出來主要是講個大致的思路

import re
import json
import demjson
import decimal


# 保存時會出現byte格式問題,使用這個處理
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        super(DecimalEncoder, self).default(o)


# 分析例子轉json,在這裡可以自己添加規則
def analyze_demjson(json_data):
    item = json_data.replace("\\n", "").replace("\\", "").replace(" ", "")
    result_item = {}
    try:
        result_item = demjson.decode(item, encoding='UTF-8')
    except:
        print(item)
    return result_item


# 獲取解析apidoc數據
def get_api_doc_data(name):
    data_list = None
    group_list = {}
    with open(name, mode='r', encoding="UTF-8") as f:
        data_list = json.load(f)
    for data in data_list:
        if data['group'] in group_list:
            group_list[data['group']].append(data)
        else:
            group_list[data['group']] = [data]
    return group_list


# 轉為swagger寫入
def set_swagger_data(data):
    swagger_json = {
        "swagger": "2.0",
        "info": {
            "description": "1.0版本介面文檔",
            "version": "1.0.5",
            "title": "智能醫療輔助平臺",
            "termsOfService": "http://swagger.io/terms/"
        },
        "host": "http://localhost:8080",
        "basePath": "/",
        "tags": [],
        "paths": {},
        "definitions": {}
    }
    # 添加分組
    for group_key in data:
        swagger_json['tags'].append({
            "name": group_key,
            "description": group_key
        })
    # 添加介面信息
    # 迴圈分組
    for group_key in data:
        # 迴圈每組列表
        for interface in data[group_key]:
            parameters = {}
            if 'parameter' in interface and 'fields' in interface['parameter']:
                # 獲取參數demo信息
                content = ""
                if 'examples' in interface['parameter']:
                    content = analyze_demjson(interface['parameter']['examples'][0]['content'])
                # 添加參數信息
                parameter_dict = {}
                for parameter in interface['parameter']['fields']['Parameter']:
                    parameter_type = "None"
                    if "type" in parameter:
                        parameter_type = parameter['type'].lower()
                        if parameter_type == 'number':
                            parameter_type = "integer"
                    parameter_item = {
                        "description": parameter['description'].replace('<p>', '').replace('</p>', ''),
                        "required": parameter['optional'],
                        "type": parameter_type,
                        "default": ''
                    }
                    if parameter['field'] in content:
                        parameter_item['default'] = content[parameter['field']]
                    parameter_dict[parameter['field']] = parameter_item
                parameters = {
                    "in": "body",
                    "name": interface['name'],
                    "description": interface['name'],
                    "required": "true",
                    "schema": {
                        "originalRef": interface['name'],
                        "$ref": "#/definitions/" + interface['name']
                    }
                }
                swagger_json['definitions'][interface['name']] = {
                        "type": "object",
                        "properties": parameter_dict
                    }
            # 添加返回信息
            responses = {
                "200": {
                    "description": "successful operation",
                    "schema": {
                        "originalRef": interface['name'] + "_response",
                        "$ref": "#/definitions/" + interface['name'] + "_response"
                    }
                }
            }
            schema = {
                "type": "object",
                "properties": {
                    "errcode": {
                        "type": "integer",
                        "default": 0,
                        "description": "編碼,成功返回1"
                    },
                    "data": {
                        "type": "object",
                        "default": {},
                        "description": "監管對象明細,包含表頭和數據內容兩部分"
                    },
                    "errmsg": {
                        "type": "string",
                        "default": "ok",
                        "description": '編碼提示信息,成功時返回 "ok"'
                    }
                }
            }
            # 返回例子
            if "success" in interface:
                response_example = ""
                if len(interface['success']['examples']) == 1:
                    response_example = analyze_demjson(interface['success']['examples'][0]['content'])
                else:
                    response_example = analyze_demjson(interface['success']['examples']['content'])
                if 'data' in response_example and response_example['data'] != {}:
                    schema['properties']['data'] = response_example['data']
            swagger_json['definitions'][interface['name'] + "_response"] = schema
            # 加入
            swagger_json['paths'][interface['url']] = {
                interface['type']: {
                    "tags": [group_key],
                    "summary": interface['title'].replace(interface['url'] + '-', ''),
                    "description": interface['title'],
                    "consumes": [
                        "application/json"
                    ],
                    "produces": [
                        "application/json"
                    ],
                    "parameters": [parameters],
                    "responses": responses
                }}
    # 寫入json文件
    with open('swagger_data.json', 'w', encoding="UTF-8") as json_file:
        json.dump(swagger_json, json_file, cls=DecimalEncoder, indent=4, ensure_ascii=False)


if __name__ == '__main__':
    group_data = get_api_doc_data('api_data.json')
    set_swagger_data(group_data)

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 聲明式事務-02 3.事務的傳播機制 事務的傳播機制說明: 當有多個事務處理並存時,如何控制? 比如用戶去購買兩次商品(使用不同的方法),每個方法都是一個事務,那麼如何控制呢? 也就是說,某個方法本身是一個事務,然後該方法中又調用了其他一些方法,這些方法也是被@Transactional 修飾的,同 ...
  • 一、前言 使用版本:QPython 3c 下載地址:百度搜索QPython 3C開源版即可下載 或關註【產品經理不是經理】gzh,回覆【qpython 3c】即可獲取下載鏈接。 二、代碼實例 註意 # 執行以下方法前,請加上以下代碼 from androidhelper import Android ...
  • 這篇文章主要關註流量回放和動態分組,主要包括流量回放的使用背景,RPC中流量回放的實現方式,動態分組要解決的問題以及如何實現動態分組。 ...
  • 簡單又高大上的項目 圖形識別、自然語言處理(語言識別、語音轉文字)、文字識別、區塊鏈 1.java實現一個基本的文字識別 引入依賴 <!-- ai 文字識別 --> <dependency> <groupId>com.baidu.aip</groupId> <artifactId>java-sdk< ...
  • 本文介紹基於Python語言,實現對多個不同Excel文件進行數據讀取與平均值計算的方法。 首先,讓我們來看一下具體需求:目前有一個文件夾,其中存放了大量Excel文件;文件名稱是每一位同學的名字,即文件名稱沒有任何規律。 而每一個文件都是一位同學對全班除了自己之外的其他同學的各項打分,我們以其中一 ...
  • 本文描述的是查找字典的某一個元素(字典遍歷元素請點擊->這裡) 上下文代碼 smart_girl = {"name":"yuan wai", "age": 25,"sex":"女"} 第一種方式:[] 註意:這種方式,如果找不到對應的key,會報一個KeyError錯誤 smart_girl["na ...
  • 日期類 一、第一代日期類 Date Date:第一代日期類,精確到毫秒,代表特定的瞬間。 SimpleDateFormat:格式化和解析日期的具體類。它允許進行格式化(日期 -> 文本)、解析(文本 -> 日期)和規範化。 SimpleDateFormat日期-時間格式模式參數: | Letter ...
  • 1. 前言 WebMvcConfigurer配置類其實是Spring內部的一種配置方式,採用JavaBean的形式來代替傳統的xml配置文件形式進行針對框架個性化定製,可以自定義一些Handler,Interceptor,ViewResolver,MessageConverter。基於java-ba ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...