Python實(shí)現(xiàn)處理apiDoc轉(zhuǎn)swagger的方法詳解
需要轉(zhuǎn)換的接口
現(xiàn)在我需要轉(zhuǎn)換的接口全是nodejs寫(xiě)的數(shù)據(jù),而且均為post傳輸?shù)膉son格式接口
apiDoc格式
apiDoc代碼中的格式如下:
/**
* @api {方法} 路徑 標(biāo)題
* @apiGroup Group
* @apiDescription 描述這個(gè)API的信息
*
* @apiParam {String} userName 用戶名
* @apiParamExample {json} request-example
* {
* "userName": "Eve"
* }
*
* @apiError {String} message 錯(cuò)誤信息
* @apiErrorExample {json} error-example
* {
* "message": "用戶名不存在"
* }
*
*
* @apiSuccess {String} userName 用戶名
* @apiSuccess {String} createTime 創(chuàng)建時(shí)間
* @apiSuccess {String} updateTime 更新時(shí)間
* @apiSuccessExample {json} success-example
* {
* "userName": "Eve",
* "createTime": "1568901681"
* "updateTime": "1568901681"
* }
*/function getUserInfo(username) {
// 假如這個(gè)函數(shù)是根據(jù)用戶名返回用戶信息的
}
使用npm安裝apidoc插件:
npm install apidoc
再新建對(duì)應(yīng)的apidoc.json,格式如下:
{
"name": "文檔名",
"version": "版本號(hào)",
"description": "解釋",
"title": "標(biāo)題",
"url" : "地址"
}
然后在apidoc.json路徑下執(zhí)行命令可以生成接口文檔(src是接口代碼文件夾,apidoc是生成文檔的文件夾):
apidoc -i src/ -o apidoc/
生成后可以在apidoc文件夾中打開(kāi)index.html查看生成的接口文檔,生成文檔時(shí)會(huì)生成一個(gè)api_data.json,下面會(huì)用到
swagger格式
這里我們暫時(shí)只需要關(guān)注參數(shù)為json的接口格式
{
"swagger": "2.0",
"info": {
"description": "1.0版本接口文檔",
"version": "1.0.5",
"title": "智能醫(yī)療輔助平臺(tái)",
"termsOfService": "http://swagger.io/terms/"
},
"host": "http://localhost:8080",
"basePath": "/",
"tags": [],
"paths": {},
"definitions": {}
}
其中path是存放接口的,tags是存放的分組名列表,definitions是實(shí)體列表(json參數(shù))
思路
使用apidoc包生成apidoc的json格式數(shù)據(jù),然后使用python讀取出接口地址、名字、組名、輸入?yún)?shù)格式和例子、輸出參數(shù)格式和例子等,然后根據(jù)swagger格式填入對(duì)應(yīng)的數(shù)據(jù)即可生成swagger的json格式
我的話是會(huì)直接使用處理出的swagger的json格式的數(shù)據(jù)導(dǎo)入yApi中
代碼
代碼雖然在下面,但是是我臨時(shí)著急用寫(xiě)的,有的地方是寫(xiě)死的,需要改,這里放出來(lái)主要是講個(gè)大致的思路
import re
import json
import demjson
import decimal
# 保存時(shí)會(huì)出現(xiàn)byte格式問(wèn)題,使用這個(gè)處理
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
return float(o)
super(DecimalEncoder, self).default(o)
# 分析例子轉(zhuǎn)json,在這里可以自己添加規(guī)則
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數(shù)據(jù)
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
# 轉(zhuǎn)為swagger寫(xiě)入
def set_swagger_data(data):
swagger_json = {
"swagger": "2.0",
"info": {
"description": "1.0版本接口文檔",
"version": "1.0.5",
"title": "智能醫(yī)療輔助平臺(tái)",
"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
})
# 添加接口信息
# 循環(huán)分組
for group_key in data:
# 循環(huán)每組列表
for interface in data[group_key]:
parameters = {}
if 'parameter' in interface and 'fields' in interface['parameter']:
# 獲取參數(shù)demo信息
content = ""
if 'examples' in interface['parameter']:
content = analyze_demjson(interface['parameter']['examples'][0]['content'])
# 添加參數(shù)信息
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": "監(jiān)管對(duì)象明細(xì),包含表頭和數(shù)據(jù)內(nèi)容兩部分"
},
"errmsg": {
"type": "string",
"default": "ok",
"description": '編碼提示信息,成功時(shí)返回 "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
}}
# 寫(xiě)入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)到此這篇關(guān)于Python實(shí)現(xiàn)處理apiDoc轉(zhuǎn)swagger的方法詳解的文章就介紹到這了,更多相關(guān)Python apiDoc轉(zhuǎn)swagger內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實(shí)現(xiàn)Word文檔樣式批量處理
這篇文章主要為大家詳細(xì)介紹了如何利用Python中的python-docx非標(biāo)準(zhǔn)庫(kù)實(shí)現(xiàn)word文檔樣式批量處理,文中示例代碼講解詳細(xì),感興趣的可以了解一下2022-05-05
Python+Pygame實(shí)戰(zhàn)之英文版猜字游戲的實(shí)現(xiàn)
這篇文章主要為大家介紹了如何利用Python中的Pygame模塊實(shí)現(xiàn)英文版猜單詞游戲,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Python游戲開(kāi)發(fā)有一定幫助,需要的可以參考一下2022-08-08
python讀取相對(duì)路徑和絕對(duì)路徑的方法
這篇文章主要介紹了python讀取相對(duì)路徑和絕對(duì)路徑,下面的路徑介紹針對(duì)windows,在編寫(xiě)的py文件中打開(kāi)文件的時(shí)候經(jīng)常見(jiàn)到下面其中路徑的表達(dá)方式,需要的朋友可以參考下2023-02-02
python基礎(chǔ)pandas的drop()用法示例詳解
這篇文章主要介紹了python基礎(chǔ)pandas的drop()用法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04
Python高級(jí)特性——詳解多維數(shù)組切片(Slice)
今天小編就為大家分享一篇Python高級(jí)特性——詳解多維數(shù)組切片(Slice),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11
python3爬蟲(chóng)GIL修改多線程實(shí)例講解
在本篇內(nèi)容里小編給大家整理的是一篇關(guān)于python3爬蟲(chóng)GIL修改多線程實(shí)例講解內(nèi)容,需要的朋友們可以參考下。2020-11-11
python實(shí)現(xiàn)各種插值法(數(shù)值分析)
這篇文章主要介紹了python實(shí)現(xiàn)各種插值法(數(shù)值分析),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
pytorch DistributedDataParallel 多卡訓(xùn)練結(jié)果變差的解決方案
這篇文章主要介紹了pytorch DistributedDataParallel 多卡訓(xùn)練結(jié)果變差的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
Python Collections強(qiáng)大的數(shù)據(jù)結(jié)構(gòu)工具使用實(shí)例探索
這篇文章主要介紹了Python Collections強(qiáng)大的數(shù)據(jù)結(jié)構(gòu)工具的使用實(shí)例探索,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01

