Flask中的redirect和url_for

 

1.  区别

url_for是个函数接受视图函数的名字(字符串形式)作为参数,返回视图函数对应的url

redirect 是重定向函数,输入一个URL后,自动跳转到另一个URL所在的地址,例如,你在函数中写 return redirect('xxxx/dsn/0') 页面就会该页面

redirect是方向导向此时浏览器需要功能就是跳转到指定的url

2、实例

@app.route('/', methods=['GET'])
def index():
    return redirect(url_for('api.index'))
@api.route('/sns', methods=["GET"])
@view_decorator("api")
def index():
    user = request.user
    type_list = TypeHandler.get_all_types()
    return render_template('index.html', **locals())

会将'/'这条URL规则和视图函数index()联系起来,并且会形成一个Rule实例,再添加进Map实例中去。当访问'/'时,会执行index()

在通过路由导向到蓝图为api下的index方法,通过url_for('api.index')反转得到url '/sns'

再就是redirect重定向请求的url就是 xxxxx/dsns

浏览器就会重新定向到此url

3、render_template() 方法

render_template() 方法来渲染模板。你需要做的一切就是将模板名和你想作为关键字的参数传入模板的变量。

return render_template('index.html', **locals())

此方法就是讲请求的参数传入到模板index.html中进行渲染

return回去首页就是index.html

4、endpoint

如果给这个装饰器再加上endpoint参数,给这个url命名

@api.route('/sns', methods=["GET"], endpoint='endpoint')
@view_decorator("api")
def index():
    user = request.user
    type_list = TypeHandler.get_all_types()
    return render_template('index.html', **locals())

一旦我们使用了endpoint参数,在使用url_for()反转的时候就不能使用视图函数名了,而是要用我们定义的url名

那么上面对应的url_for('api.index'),就需要改成 api.endpoint了

上一篇:asp.net core 3.x Endpoint终结点路由1-基本介绍和使用


下一篇:用 np.logspace() 创建等比数列