1、add_url_rule
add_url_rule(rule,endpoint=None,view_func=None)
这个方法用来添加url与视图函数的映射。
如果没有填写 endpoint ,那么默认会使用 view_func 的名字作为 endpoint 。
以后在使用 url_for 的时候,就要看在映射的时候有没有传递 endpoint 参数,如果传递了,那么就应该使用 endpoint 指定的字符串;如果没有传递,那么就应该使用 view_func 的名字。
def show_me():
return "这个介绍信息!!"
# endpoint 没有设置,url_for中就写函数的名字,如果设置了,就写endpoint的值
app.add_url_rule('/show_me', view_func=show_me, endpoint='show')
# @app.route 底层就是使用的 add_url_rule
2、app.route原理剖析
这个装饰器底层,其实也是使用 add_url_rule 来实现url与视图函数映射的。
示例代码:
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/', endpoint='index')
def index():
print(url_for('show'))
print(url_for('index'))
return "Hello"
def show_me():
return "这个介绍信息!!"
# endpoint 没有设置,url_for中就写函数的名字,如果设置了,就写endpoint的值
app.add_url_rule('/show_me', view_func=show_me, endpoint='show')
# @app.route 底层就是使用的 add_url_rule
if __name__ == '__main__':
app.run(debug=True)
运行结果: