当前位置: 代码迷 >> 综合 >> flask 中 add_url_rule和app.route
  详细解决方案

flask 中 add_url_rule和app.route

热度:11   发布时间:2023-11-27 21:51:18.0

add_url_rule和app.route原理剖析

`add_url_rule(rule,endpoint=None,view_func=None)`

         这个方法用来添加url与视图函数的映射。如果没有填写`endpoint`,那么默认会使用`view_func`的名字作为`endpoint`。以后在使用`url_for`的时候,就要看在映射的时候有没有传递`endpoint`参数,如果传递了,那么就应该使用`endpoint`指定的字符串,如果没有传递,那么就应该使用`view_func`的名字。

     例:

def my_list():

    return "我是列表页"

app.add_url_rule('/list/',endpoint='sxt',view_func=my_list)

`app.route(rule,**options)`装饰器:

这个装饰器底层,其实也是使用`add_url_rule`来实现url与视图函数映射的。

from flask import Flask,url_for
app = Flask(__name__)@app.route('/',endpoint='hello')
def hello_world():#构建url  :/list/#研究app.add_url_rule()方法,若方法中【没有加】上endpoint时,可通过原来的函数名构建url,即url_for('原函数名')# print(url_for('my_list'))#研究app.add_url_rule()方法,若方法中【加上】endpoint时,不能再通过原来的函数名构建url,而需要endpoint的值才行# 即url_for('endpoint值')print(url_for('li'))return 'Hello World!'def my_list():return   "这是列表页"#通过app对象的add_url_rule方法 来完成url与视图函数的映射
app.add_url_rule('/list/',endpoint='li',view_func = my_list)#讨论:add_url_rule()方法  与@app.route()装饰器的关系
#结论:@app.route()装饰器 底层就是借助于add_url_rule()方法来实现的#请求上下文对象     项目一启动就会执行
with  app.test_request_context():# print(url_for('hello_world'))print(url_for('hello'))if __name__ == '__main__':app.run(debug=True)

  相关解决方案