移动 Flask-Restplus Swagger API 文档

Move Flask-Restplus Swagger API Docs

我正在尝试使用 flask-restplus 在 python 中构建 restful API。我想让 swagger 文档位于与普通“/”不同的位置。

我正在遵循文档 here 并已按照说明进行操作。我正在使用 python2.7.3 并具有以下代码 ~/dev/test/app.py:

from flask import Flask
from flask.ext.restplus import Api, apidoc

app = Flask(__name__)
api = Api(app, ui=False)

@api.route('/doc/', endpoint='doc')
def swagger_ui():
    return apidoc.ui_for(api)

app.register_blueprint(apidoc.apidoc)

当我尝试 运行 这个 python app.py 我得到:

Traceback (most recent call last):
  File "app.py", line 7 in <module>
    @api.route('/doc/', endpoint='doc')
  File "/home/logan/.virtualenvs/test/lib/python2.7/site-packages/flask_restplus/api.py", line 191, in wrapper
    self.add_resources(cls, *urls, **kwargs)
  File "/home/logan/.virtualenvs/test/lib/python2.7/site-packages/flask_restplus/api.py", line 175, in add_resource
    super(Api, self).add_resource(resource, *urls, **kwargs)
  File "/home/logan/.virtualenvs/test/lib/python2.7/site-packages/flask_restful/__init__.py", line 396, in add_resource
    self._register_view(self.app, resource, *urls, **kwargs)
  File "/home/logan/.virtualenvs/test/lib/python2.7/site-packages/flask_restful/__init__.py", line 435, in _register_view
    resource_func = self.output(resource.as_view(endpoint, *resource_class_args,
AttributeError: 'function' object has no attribute 'as_view'

我不太确定到底出了什么问题,我想我明白我没有继承自 Resourceas_view 通常来自哪里,但文档似乎表明这应该有效。

如有任何帮助,我们将不胜感激。

最近我自己也在努力解决这个问题,我很幸运地采用了这种方法:

from flask import Flask, Blueprint
from flask.ext.restplus import Api, apidoc

app = Flask(__name__)

blueprint = Blueprint('api', __name__)
api = Api(blueprint, ui=False)

@blueprint.route('/doc/', endpoint='doc')
def swagger_ui():
   return apidoc.ui_for(api)

app.register_blueprint(blueprint)

对于 Flask-Restplus <= 0.8.0 你应该这样写:

from flask import Flask
from flask.ext.restplus import Api, apidoc

app = Flask(__name__)
api = Api(app, ui=False)

@app.route('/doc/', endpoint='doc')
def swagger_ui():
    return apidoc.ui_for(api)

注意使用 @app 而不是 @api

从 v0.8.1(即将发布)开始,您只需编写:

from flask import Flask
from flask.ext.restplus import Api, apidoc

app = Flask(__name__)
api = Api(app, doc='/doc/')

参见:http://flask-restplus.readthedocs.org/en/latest/swagger.html#swagger-ui

看起来@api 需要资源,所以我稍微修改了代码以解决该错误。以下仅适用于 /doc/,不适用于默认根级别。

from flask import Flask, make_response
from flask.ext.restplus import Api, apidoc, Resource

app = Flask(__name__)
api = Api(app, ui=False)

@api.route('/doc/', endpoint='doc', doc=False)
class ApiDoc(Resource):
    def get(self):
        return make_response(apidoc.ui_for(api))

app.register_blueprint(apidoc.apidoc)

if __name__ == '__main__':
    app.run(debug=True)