之前我们使用@app.route这个装饰器来把视图函数和url绑定
@app.route('/')
def hell_world():
return 'hello world'
而且我们可以通过url_for(‘hello_world‘)
反转得到url /
实际上我们可以给这个装饰器再加上endpoint参数,给这个url
命名
# simple1
@app.route('/', endpoint='index')
def hello_word():
return 'hello world'
一旦我们指定了endpoint
参数,则在使用url_for()
反转的时候就不能使用视图函数名了,而是要用我们定义的url名,即endpoint
参数值
url_for('index')
另外一种方式绑定视图函数和url,那就是add_url_rule
。
因此,我们可以这样用
# simple2
def my_list():
return 'my list'
app.add_url_rule(rule='/list/', endpoint='list', view_func=my_list)
如果要使用url_for
反转的话,也是:url_for('list')
,而不是url_for('my_list')
,因为在映射这个函数与url时,设置了endpoint='list'
。
以上内容参考整理自:add_url_rule和app.route原理及知了课堂黄勇老师讲解的flask进阶-vip课程