如题, add_url_rule 怎么添加多个网址呢?类似的例子如下:
from flask import MethodView
from flask import Blueprint
from .. import app
admin = Blueprint("admin", __name__, static_folder="static", url_prefix="/admin")
class AdminViewIndex(MethodView):
methods = ["GET"]
def get(self):
return "<h1>这是管理后台页面</h1>"
admin.add_url_rule(rule="/", endpoint="admin", view_func=AdminViewIndex.as_view(Index))
app.register_blueprint(admin)
如上述代码,这样只能将 AdminViewIndex 注册到 127.0.0.1/admin/ 网址上,如何将它同时也注册到 127.0.0.1/admin/index 上呢?
我自己测试过在加上一条 add_url_rule 规则如下:
admin.add_url_rule(rule="/index", endpoint="admin", view_func=AdminViewIndex.as_view(index))
这样两条规则同时存在的情况下是可以 注册到两个网址上的,如何一条 add_url_rule 注册两个网址呢? 请各位大神指教,谢谢!
那就你写2条规则就好啦
在这个例子中,endpoint
建议不要使用admin
值,可以尝试使用index
或者adminindex
等(endpoint
一般和视图函数名称相同):
python
admin.add_url_rule(rule="/", endpoint="index", view_func=AdminViewIndex.as_view(Index)) admin.add_url_rule(rule="/index", endpoint="index", view_func=AdminViewIndex.as_view(Index))
add_url_rule
是单数操作,只能一条一条加。
再举个例子(下面两个写法是等价的):
pyhton
@app.route('/') @app.route('/index') def index(): pass
等价于:
python
def index(): pass app.add_url_rule('/', 'index', index) app.add_url_rule('/index', 'index', index)