问题
I'm trying to use Flask-Restplus to make an api and document it with swagger.
This is what I have so far and it works fine except I do not know how to add a root route.
from flask import Flask, Blueprint
from flask_restplus import Api, Resource, apidoc
app = Flask('__name__')
blueprint = Blueprint('v1', __name__, url_prefix='/rest/v1')
api = Api(blueprint, ui=False, version='1.0')
@blueprint.route('/apidoc/', endpoint='apidoc')
def swagger_ui():
return apidoc.ui_for(api)
@blueprint.route('/', endpoint='rootres')
def root():
return ''
app.register_blueprint(blueprint)
ns = api.namespace('test', description='desc')
@ns.route('/', endpoint='rootresource')
class RootResource(Resource)
def get(self):
...
while /rest/v1/test works fine, /rest/v1 gives me Page not found.
if I modify like this:
@blueprint.route('/aaa', endpoint='rootres')
def root():
return ''
then /rest/v1/aaa works.
Question: how can I make @blueprint.route('/') work?
回答1:
When you wrote ui=False
you disabled the /rest/v1/
path.
In the next coming release (the 0.8.1 for the end of this week), you should be able to write:
from flask import Flask, Blueprint
from flask_restplus import Api, Resource
app = Flask('__name__')
blueprint = Blueprint('v1', __name__, url_prefix='/rest/v1')
api = Api(blueprint, doc='/apidoc/', version='1.0')
@blueprint.route('/', endpoint='rootres')
def root():
return ''
ns = api.namespace('test', description='desc')
@ns.route('/', endpoint='rootresource')
class RootResource(Resource)
def get(self):
...
app.register_blueprint(blueprint)
No need anymore to register a specific view for the documentation
For the `blueprint.route('/'), I think this is fixed by 0.8.1 too.
Note: register the blueprint later, after namespaces import/declaration.
回答2:
I found very similar problem. I wanted make '/' route with custom page, and swagger doc on different path.
My first attempt (Not working)
from flask import Flask
from flask_restplus import Api
app = Flask(__name__)
api = Api(
app= app,
version='1.0',
description='TEST API',
doc='/docs/',
)
@app.route('/')
def hello():
return "Hello on my page"
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
Page http://127.0.0.1:5000/
return 404 error
Working example
from flask import Flask
from flask_restplus import Api
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello on my page"
api = Api(
app= app,
version='1.0',
description='TEST API',
doc='/docs/',
default='mapi',
default_label='Super API'
)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
Tested on:
- Python 3.6.1
- Flask (0.12.1)
- flask-restplus (0.10.1)
来源:https://stackoverflow.com/questions/32477878/flask-restplus-route