【问题标题】:How to use Flasgger with Flask applications using Blueprints?如何在使用蓝图的 Flask 应用程序中使用 Flasgger?
【发布时间】:2017-05-27 00:44:49
【问题描述】:

我正在使用 Flasgger 将 Swagger UI 添加到我的 Python Flask 应用程序中。 Internet 上最常见的示例是使用 @app.route 的基本 Flask 样式:

from flasgger.utils import swag_from

@app.route('/api/<string:username>')
@swag_from('path/to/external_file.yml')
def get(username):
    return jsonify({'username': username})

这行得通。

然而,在我的应用程序中,我没有使用 @app.route 装饰器来定义端点。我正在使用烧瓶蓝图。如下:

from flask import Flask, Blueprint
from flask_restful import Api, Resource
from flasgger.utils import swag_from
...

class TestResourceClass(Resource):

      @swag_from('docs_test_get.yml', endpoint='test')   
      def get() :
         print "This is the get method for GET /1.0/myapi/test endpoint"

app = Flask(__name__)
my_api_blueprint = Blueprint('my_api', __name__)
my_api = Api(my_api_blueprint)

app.register_blueprint(my_api_blueprint, url_prefix='/1.0/myapi/')

my_api.add_resource(TestResourceClass, '/test/'
                        endpoint='test',
                        methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
....

如上所示,我在绑定到 GET 方法端点的 TestResourceClass.get() 方法上使用了 @swag_from 装饰器。我在这两个地方也有 endpoint=test 匹配。

但是我在 Swagger UI 上什么都没有,全是空白的。 docs_test_get.yml 文件确实包含有效的 yaml 标记来定义 swagger 规范。

我错过了什么?如何让 Flasgger Swagger UI 与基于 Flask 蓝图的设置一起使用?

【问题讨论】:

标签: python flask swagger swagger-ui


【解决方案1】:

您只需要在引用端点时添加您的蓝图名称。蓝图创建命名空间。下面的例子。有用的提示:使用app.logger.info(url_for('hello1')) 调试端点问题 - 它会显示非常有用的错误消息,例如Could not build url for endpoint 'hello1'. Did you mean 'api_bp.hello1' instead?

from flask import Flask, Blueprint, url_for
from flask_restful import Api, Resource
from flasgger import Swagger, swag_from

app = Flask(__name__)
api_blueprint = Blueprint('api_bp', __name__)
api = Api(api_blueprint)


class Hello(Resource):

    @swag_from('hello1.yml', endpoint='api_bp.hello1')
    @swag_from('hello2.yml', endpoint='api_bp.hello2')
    def get(self, user=''):
        name = user or 'stranger'
        resp = {'message': 'Hello %s!' % name}
        return resp


api.add_resource(Hello, '/hello', endpoint='hello1')
api.add_resource(Hello, '/hello/<string:user>', endpoint='hello2')

app.register_blueprint(api_blueprint)
swagger = Swagger(app)

app.run(debug=True)


【讨论】:

  • 谢谢,这在flasgger 文档和示例中完全不清楚。
【解决方案2】:

似乎 flasgger 不起作用或对蓝字样式 Flask 定义没有适当的支持(目前)。我使用了https://github.com/rantav/flask-restful-swagger,效果很好!

【讨论】:

    【解决方案3】:

    现在https://github.com/rochacbruno/flasgger/blob/master/examples/example_blueprint.py中有一个蓝图应用示例

    """
    A test to ensure routes from Blueprints are swagged as expected.
    """
    from flask import Blueprint, Flask, jsonify
    
    from flasgger import Swagger
    from flasgger.utils import swag_from
    
    app = Flask(__name__)
    
    example_blueprint = Blueprint("example_blueprint", __name__)
    
    
    @example_blueprint.route('/usernames/<username>', methods=['GET', 'POST'])
    @swag_from('username_specs.yml', methods=['GET'])
    @swag_from('username_specs.yml', methods=['POST'])
    def usernames(username):
        return jsonify({'username': username})
    
    
    @example_blueprint.route('/usernames2/<username>', methods=['GET', 'POST'])
    def usernames2(username):
        """
        This is the summary defined in yaml file
        First line is the summary
        All following lines until the hyphens is added to description
        the format of the first lines until 3 hyphens will be not yaml compliant
        but everything below the 3 hyphens should be.
        ---
        tags:
          - users
        parameters:
          - in: path
            name: username
            type: string
            required: true
        responses:
          200:
            description: A single user item
            schema:
              id: rec_username
              properties:
                username:
                  type: string
                  description: The name of the user
                  default: 'steve-harris'
        """
        return jsonify({'username': username})
    
    
    app.register_blueprint(example_blueprint)
    
    swag = Swagger(app)
    
    if __name__ == "__main__":
        app.run(debug=True)
    

    【讨论】:

      【解决方案4】:

      swag_from 函数解析文件路径时出错。您可以先使用 doc 字符串在 get() 中定义 api。 flasgger 将解析 MethodView() 方法,如 get,post。

      【讨论】:

      • 我测试了文件路径在 swag_from 中用于非蓝图样式 api 定义时不是问题。
      猜你喜欢
      • 1970-01-01
      • 2017-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-18
      • 1970-01-01
      相关资源
      最近更新 更多