[英]Regarding the problem of the route function according to the API object declaration location of Flask_restx
Flask restx 是一個在flask框架中通過分文件來開發api函數的庫,支持swaggerui。 在一台flask服務器上服務api和網頁時,api部分可以拆分成文件,使用restx開發。 但是,注冊命名空間來編寫flask restx 時有一個注意事項。 下面兩個源碼的區別是api的namespace注冊部分和api的app.route函數部分,api的namespace注冊部分是在app.route之前還是之后。
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)
首先,當用第一個源代碼執行時,通常在接近 / 和 /test 路徑時識別。
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 -
但是,第二個源代碼只能正常識別 /test 而 / 不能識別。
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 -
可以看到控制台日志和網頁瀏覽器在接近/路由時也顯示404錯誤。 但是,在第二個源代碼中,並非所有 / 的子路由都是不可能的。
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)
這樣, /root 不識別,但 /main 識別。
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 -
我不知道他們為什么這樣做。
嘗試將路由字符串留空以查看是否有效
@app.route('')
def index():
return 'index'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.