使用 Flask-Docs 自动生成 Api 文档

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/z497896143/article/details/81073044

影响我写文档的原因可能是代码和文档分离,有时候写完代码会忘记补文档,而且不能及时查看,使用 Flask-Docs 可以解决我的问题,这个插件可以根据代码注释生成文档页面,代码注释改动文档可以及时更新,而且支持离线文档下载。

Flask-Docs

Flask Api 文档自动生成插件

特性

  • 根据代码注释自动生成文档
  • 支持 Flask-RESTful
  • 支持离线 markdown 文档下载

安装

pip install Flask-Docs

使用

from flask import Flask
from flask_docs import ApiDoc

app = Flask(__name__)

# 本地加载
# app.config['API_DOC_CDN'] = False

# 禁用文档页面
# app.config['API_DOC_ENABLE'] = False

# 需要显示文档的 Api
app.config['API_DOC_MEMBER'] = ['api', 'platform']

# 需要排除的 RESTful Api 文档
app.config['RESTFUL_API_DOC_EXCLUDE'] = []

ApiDoc(app)

如何书写 markdown 格式文档

@@@
在注释结尾用 “@@@” 包含 markdown 格式文档
@@@

查看文档页面

http://127.0.0.1/docs/api

Api demo

@api.route('/add_data', methods=['POST'])
def add_data():
    """Add some data

    Add some data in this routing

    Args:
        pass

    Returns:
        pass
    """
    return jsonify({'api': 'add data'})

这里写图片描述

@api.route('/del_data', methods=['POST'])
def del_data():
    """Del some data

    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    title    |    false    |    string   |    blog title    |
    |    name    |    true    |    string   |    person's name    |

    #### return
    - ##### json
    > {"msg": "success", "code": 200}
    @@@
    """
    return jsonify({'api': 'del data'})

这里写图片描述

@platform.route('/get_something', methods=['GET'])
def get_something():
    """
    @@@
    #### example
    ```
    import requests
    url='http://127.0.0.1:5000/api/get_something'
    try:
        print requests.get(url).text
    except:
        pass
    ```
    @@@
    """
    return jsonify({'platform': 'get something'})

这里写图片描述

完整代码

#!/usr/bin/env python
# -*- coding:utf-8 -*-

from flask import Flask, render_template, jsonify, Blueprint
from flask_docs import ApiDoc

app = Flask(__name__)

# Local loading
# app.config['API_DOC_CDN'] = False

# Disable document pages
# app.config['API_DOC_ENABLE'] = False

# Api Document needs to be displayed
app.config['API_DOC_MEMBER'] = ['api', 'platform']

ApiDoc(app)

api = Blueprint('api', __name__)
platform = Blueprint('platform', __name__)


@api.route('/add_data', methods=['POST'])
def add_data():
    """Add some data

    Add some data in this routing

    Args:
        pass
 
    Returns:
        pass
    """
    return jsonify({'api': 'add data'})


@api.route('/del_data', methods=['POST'])
def del_data():
    """Del some data

    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    title    |    false    |    string   |    blog title    |
    |    name    |    true    |    string   |    person's name    |

    #### return
    - ##### json
    > {"msg": "success", "code": 200}
    @@@
    """
    return jsonify({'api': 'del data'})


@platform.route('/get_something', methods=['GET'])
def get_something():
    """
    @@@
    #### example
    ```
    import requests
    url='http://127.0.0.1:5000/api/get_something'
    try:
        print requests.get(url).text
    except:
        pass
    ```
    @@@
    """
    return jsonify({'platform': 'get something'})


app.register_blueprint(api, url_prefix='/api')
app.register_blueprint(platform, url_prefix='/platform')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

Flask-RESTful Api demo

from flask_restful import Resource, Api

class TodoList(Resource):
    """Manage todolist"""

    def post(self):
        """Submission of data

        Args:
            pass

        Returns:
            pass

        """
        return {'todos': 'post todolist'}

    def get(self):
        """
        @@@
        #### args

        | args | nullable | type | remark |
        |--------|--------|--------|--------|
        |    id    |    false    |    int   |    todo id    |

        #### return
        - ##### json
        > {...}
        @@@
        """
        return {'todos': 'get todolist'}


restful_api.add_resource(TodoList, '/todolist')

这里写图片描述
这里写图片描述

完整代码

#!/usr/bin/env python
# -*- coding:utf-8 -*-

from flask import Flask
from flask_restful import Resource, Api
from flask_docs import ApiDoc

app = Flask(__name__)

# Local loading
# app.config['API_DOC_CDN'] = False

# Disable document pages
# app.config['API_DOC_ENABLE'] = False

# RESTful Api documents to be excluded
app.config['RESTFUL_API_DOC_EXCLUDE'] = []

restful_api = Api(app)
ApiDoc(app)


class TodoList(Resource):
    """Manage todolist"""

    def post(self):
        """Submission of data

        Args:
            pass
    
        Returns:
            pass

        """
        return {'todos': 'post todolist'}

    def get(self):
        """
        @@@
        #### args

        | args | nullable | type | remark |
        |--------|--------|--------|--------|
        |    id    |    false    |    int   |    todo id    |

        #### return
        - ##### json
        > {...}
        @@@
        """
        return {'todos': 'get todolist'}


restful_api.add_resource(TodoList, '/todolist')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
展开阅读全文

没有更多推荐了,返回首页