4

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

我正在关注此处的文档并已按照说明进行操作。我正在使用 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'

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

任何帮助将不胜感激。

4

3 回答 3

6

使用 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)

注意使用 a@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

于 2015-10-14T21:21:51.753 回答
2

在最近自己为此苦苦挣扎之后,我对这种方法很幸运:

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)
于 2015-09-01T00:25:36.230 回答
0

看起来@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)
于 2015-11-19T05:41:47.257 回答