Flask restx is a library that develops api functions by dividing them into files in the flask framework and supports swaggerui. When serving api and web pages on one flask server, the api part can be divided into files and developed using restx. However, there is a caution when registering namespace to write flask restx. The difference between the two source codes below is whether the namespace registration part of api and the app.route function part of api, and whether the namespace registration part of api comes before the app.route or later.
from flask import Flask, render_template, url_for
from datetime import datetime
from flask_restx import Api
from test import test
app = Flask(__name__)
@app.route('/')
def index():
return 'index'
api = Api(
app,
doc="/doc/",
version="0.1",
title="test",
)
api.add_namespace(test, '/test')
if __name__ == '__main__':
app.run(debug=True)
from flask import Flask, render_template, url_for
from datetime import datetime
from flask_restx import Api
from test import test
app = Flask(__name__)
api = Api(
app,
doc="/doc/",
version="0.1",
title="test",
)
api.add_namespace(test, '/test')
@app.route('/')
def index():
return 'index'
if __name__ == '__main__':
app.run(debug=True)
First, when executed with the first source code, it is normally recognized when approaching the / and /test path.
127.0.0.1 - - [27/Sep/2021 15:40:40] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [27/Sep/2021 15:40:40] "GET /test HTTP/1.1" 404 -
However, the second source code recognizes only /test normally and / does not.
127.0.0.1 - - [27/Sep/2021 15:40:40] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [27/Sep/2021 15:40:40] "GET /test HTTP/1.1" 200 -
It can be seen that the console log and web browser are also displaying 404 errors when approaching / route. However, in the second source code, not all of the subroutes of / are not possible.
from flask import Flask, render_template, url_for
from datetime import datetime
from flask_restx import Api
from test import test
app = Flask(__name__)
api = Api(
app,
doc="/doc/",
version="0.1",
title="test",
)
api.add_namespace(test, '/test')
@app.route('/')
def index():
return 'index'
@app.route('/main')
def main():
return 'main'
if __name__ == '__main__':
app.run(debug=True)
In this way, / root is not recognized, but /main recognizes.
127.0.0.1 - - [27/Sep/2021 15:40:35] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [27/Sep/2021 15:40:40] "GET /test HTTP/1.1" 200 -
127.0.0.1 - - [27/Sep/2021 15:40:45] "GET /main HTTP/1.1" 200 -
I don't know why they do this.