无法使用Flask Restplus注册蓝图

时间:2019-08-14 01:55:02

标签: python flask flask-restplus

因此,当所有这些都放在一个文件中时,webapp和API一样可以正常工作,我可以看到文档。我希望将API分成一个单独的文件。但是我得到一个错误:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
    app.register_blueprint(GetResource)
  File "/home/jj/mysite/lib/python3.6/site-packages/flask/app.py", line 66, in wrapper_func
    return f(self, *args, **kwargs)
  File "/home/jj/mysite/lib/python3.6/site-packages/flask/app.py", line 1102, in register_blueprint
    if blueprint.name in self.blueprints:
AttributeError: type object 'GetResource' has no attribute 'name'

这是project/main.py处的示例代码:

#! /usr/bin/python3
from flask import Flask, render_template
from datetime import timedelta
from utils.api_methods import GetResource

app = Flask(__name__)
app.config.SWAGGER_UI_DOC_EXPANSION = 'full'
app.register_blueprint(GetResource)
app.secret_key = 'xxxxxxxxxxxxxxxxxxxxxxxx'
app.permanent_session_lifetime = timedelta(minutes=1)


@app.route('/', methods=['POST', 'GET'])
def index():
    return render_template("index.html")


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

这是project / utils / api_methods.py:

from flask import request
from flask import Blueprint, jsonify, make_response
from flask_restplus import Resource, Api


blueprint = Blueprint('api', __name__, url_prefix='/api')
api = Api(
    blueprint, doc='/', version='1.0',
    title='Testing Blueprints',
    description="Try the API")
api.namespaces = []
ns = api.namespace('', description='test')
parser1 = api.parser()
parser1.add_argument(
    'Path',
    location='headers',
    help='Path to file or directory',
    required=True
)


@ns.route('/resources')
@api.route('/resources')
@api.doc(parser=parser1)
class GetResource(Resource):
    def get(self):
        ...
        return jsonify({'SUCCESS': 'endpoint accessed'})

1 个答案:

答案 0 :(得分:0)

您必须注册蓝图而不是资源类,就像方法register_blueprint所暗示的那样。

from utils.api_methods import blueprint

...

app.register_blueprint(blueprint)