[Flask教程] 2.反转函数url_for与重定向redirect

在flask中,我们导入url_for和redirect两个函数。

from flask import Flask, url_for, redirect   

首先看url_for,简单来说,这个函数接受视图函数的名字(字符串形式)作为参数,返回视图函数对应的url,例如:

@app.route('/')
def hello_world():
    print(url_for('index'))
    return 'Hello World'

@app.route('/index/')
def index():
    return 'index'

在hello_world函数中使用print(url_for(‘index’)),将会打印出/index/。
有传参的视图函数怎么办?同样将函数名字符串作为第一个参数,将参数以key=value的形式写在后面,如:

@app.route('/')
def hello_world():
    print(url_for('hello',name='harp'))
    return 'Hello World'

@app.route('/<name>/')
def hello(name):
    return 'Hello %s' % name

打印结果为/harp/。

redirect则更简单,功能就是跳转到指定的url,大部分情况下,我们都是和url_for一起使用的,例如:

@app.route('/')
def hello_world():
    return 'Hello World'


@app.route('/<name>/')
def hello(name):
    if name == 'Harp':
        return 'Hello %s' % name
    else:
        return redirect(url_for('hello_world'))

在hello这个视图函数中,如果url传入的参数是Harp(即请求的网址是http://127.0.0.1:5000/Harp/),则返回’Hello Harp’,其他情况则重定向到hello_world这个视图函数对应的网址’/’。

标签:Flask 发布于:2019-10-29 21:34:07