So when all this is put into one file, the webapp works as well as the API and I am able to see the documentation. I wish to separate the API into a separate file. However I get an error:
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'
Here is the example code at 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)
and here is 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'})
You have to register the blueprint, not the resource class, as the name of the method register_blueprint
implies.
from utils.api_methods import blueprint
...
app.register_blueprint(blueprint)