flask使用restful接口風格之-flask-restx的使用


簡介

flask-restx是一個支持RESTFulflask插件。

用於規范化接口的編寫,並且支持 swagger文檔。

github地址 官方文檔地址

使用說明

下載

pip install flask-restx

示例代碼

示例代碼以一個使用藍圖的程序為例。其他小的應用可參看 flask-restx官方示例

項目結構

.
├── config.py
├── log    
├── manage.py  # 啟動入口
├── server
│   ├── __init__.py
│   ├── api.py
│   ├── apis
│   │   └── test
│   │       ├── api.py
│   │       └── web.py
│   ├── static
│   └── templates
└── utils
    └── db.py

實踐代碼:

# server  __init__.py
from flask import Flask

def create_app():
    # 創建Flask對象
    app = Flask(__name__)
    # 注冊藍圖
    from server.api import api_v1
    app.register_blueprint(api_v1)
    return app
# server api.py
from flask import Blueprint
from flask_restx import Api
from server.apis.test.web import ns as test_ns


api_v1 = Blueprint('api1', __name__, url_prefix='/api')

api = Api(
    api_v1, 
    version='1.0', 
    title='test flask',
    description='test flask'
)

api.add_namespace(test_ns)
# server apis test web.py
import json
from flask import request, render_template, make_response, jsonify
from flask_restx import Namespace, Resource, fields


ns = Namespace('test', description='test')


@ns.route("", strict_slashes=False)  # 實際訪問地址 /api/test/
class TestHandler(Resource):

    def get(self):
        # 如果使用模板的塊,需要使用 make_response
        # return make_response(render_template('index.html', data=res), 200)
        
        # 使用 jsonify 是為了返回json數據的同時,相比於 json.dumps() 其會自動修改 content-type 為 application/json
        # 另外,如果使用 jsonify()的同時,還想自定義返回狀態碼,可以使用 make_response(jsonify(data=data), 201)
        return jsonify()
    
    def post(self):
        pass
    
    def put(self):
        pass
    
    def delete(self):
        pass

代碼說明

  1. 使用 flask-restx之后,可以使用類視圖的方式定義接口.
  2. 可以訪問 localhost:5000/api訪問 swagger接口文檔頁面。
  3. 接口文檔可以在編寫代碼的地方一起定義。

swagger文檔編寫方式

以上面 TestHandler類方法為基礎,定義以下較為常用的文檔。

通常情況下,restful接口默認返回的都是json數據。因此以下文檔針對json數據。

所有定義文檔都可以在瀏覽器訪問 /api/ 查看

對於前后端不分離的 templates 等模板文檔,可能有不正確的地方。

1. 參數以url形式
@ns.route("/<id>", strict_slashes=False)  # 實際訪問地址 /api/test/1
@ns.doc(params={'id': 'An ID'})
class TestHandler(Resource):

    def get(self, id):
        return jsonify()
    
    @ns.doc(response={403: 'Not Authorized'})
    def post(self, id):
        pass
2. 參數以json body的形式
parent = ns.model('Parent', {
    'name': fields.String,
    'age': fields.Integer(discriminator=True),
    'addr': fields.String(description='地址'),
    'gender': fields.String(description='性別', required=True, enum=['男', '女', '未知'])
})

child = ns.inherit('Child', parent, {
    'extra': fields.String
})
@ns.route("/test3", strict_slashes=False)  # /api/test/test3
class Test2Handler(Resource):

    @ns.marshal_with(child, as_list=True)  # 等價於 @api.marshal_list_with(resource_fields)
    def get(self):
        return "返回一個對象"
    
    @ns.marshal_with(child, code=201)  # 201 代表創建成功
    def post(self):
        return '創建一個對象成功', 201
3. 其他

flask-restx提供了許多文檔定制功能。每個功能都有不同的寫法。如:

  1. 某個請求默認需要某些參數,並且要驗證 ===>@ns.expect(resource_fields, validate=True)
  2. 給已知響應定義默認響應-- @ns.response()
  3. url路徑文檔===》@ns.route('', doc='') 或者 @ns.doc()
  4. 可使用多個 @ns.route() 裝飾一個函數,使得多個url定位到一個Handler處理
  5. 給參數定義文檔。如上文的json body 形式中的parent
  6. method定義文檔
  7. 定義 headers定義文檔
  8. 隱藏某些文檔
  9. 文檔授權
  10. 其他

具體文檔可點flask-restx官方文檔了解

RESTful接口風格說明

具體說明可參看阮一峰博客

坑點:此接口風格對批量處理的支持並不友好。解決此問題可參看RESTful API批量操作的實現


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM