flask項目集成swagger

   此次主要介紹介紹在flask框架中如何集成swagger文檔, 我們知道以前給同事提供接口文檔主要是寫一個文檔, 當遇到頻繁修改時,就需要更新文檔非常麻煩, 這時swagger文檔就出現了,一個在線得接口文檔,同事可以在線上查看接口文檔, 當需要修改接口時秩序修改對應得代碼,文檔也會隨之更新。如下圖所示。

 

 

 

 

  此次集成參考flask-restplus官方文檔,flask-restplus框架是flask-restful框架的一個加強版, 類似django框架的rest framework框架,應用前得先安裝框架執行命令:

 pip install flask-restplus

  

  然後結合官網寫個簡單示例感受一下:

from flask import Flask
from flask_restplus import Api, Resource, fields, reqparse

app = Flask(__name__)
api = Api(app, version='1.0', title='TodoMVC API', description='A simple TodoMVC API',)

ns = api.namespace('todo', description='TODO operations')                              # 模塊命名空間

todo = api.model('Todo', {                                                             # 返回值模型
    'id': fields.Integer(readonly=True, description='The task unique identifier'),
    'task': fields.String(required=True, description='The task details')
})

parser = reqparse.RequestParser()                                            # 參數模型
parser.add_argument('id', type=str, required=True, help="id")
parser.add_argument('name', type=str, required=True, help="名稱")
parser.add_argument('volume', type=int, required=True, help="方量")


class TodoDAO(Resource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.params = parser.parse_args()

    @ns.expect(parser)                                    # 用於解析對應文檔參數,                         
    @ns.response(200, "success response", todo)            # 對應解析文檔返回值
    def get(self):
        return self.params


ns.add_resource(TodoDAO, "/to", endpoint="to_do")

app.run()

 

 

我們啓動得地址爲127.0.0.1:5000得地址, 然後我們只需在瀏覽器打開即可查看自己寫好得api文檔,如下圖:

 

 

好了,至此我們已經集成好了swagger文檔, 需要更詳細得內容可以參考官網文檔, 比方更改文檔地址等。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章