通过url_for视图函数反向解析路由地址

url_for

  作用:通过视图函数反向解析路由地址。

from flask import Flask, redirect, url_for

app = Flask(__name__)


@app.route('/')
def index():
    return 'hello flask,测试302临时重定向!'


@app.route('/cx/<name>/<age>/')
def test(name, age):
    return '我的名字是{},我今年{}岁'.format(name, age)


@app.route('/test_redirect/')
# 302临时重定向视图函数
def test_redirect():
    return redirect('/cx/python/3.9/')


@app.route('/r_test_redirect/')
# 通过url_for解析地址,就算路由地址改变,参数名称不变就可以找到
def r_test_redirect():
    # url_for通过视图函数反向解析路由地址
    # 寻找test函数且具有name='python', age=3.9参数
    # 但url_for无法单独使用
    # return url_for('test', name='python', age=3.9)
    # 这里的test是视图函数名称
    return redirect(url_for('test', name='python', age=3.9))


if __name__ == "__main__":
    app.run(debug=True)

 

原文地址:https://www.cnblogs.com/cxstudypython/p/12493038.html