Python Flask:使用 redirect 重定向网址


#Python Flask Web 框架#


本文讲述在 Python Flask Web 框架中如何重定向网址。

redirect函数用于重定向,实现机制很简单,就是向客户端(浏览器)发送一个重定向的HTTP报文,浏览器会去访问报文中指定的url。

建立Flask项目

按照以下命令建立Flask项目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

编写代码

使用redirect时,给它一个字符串类型的参数就行了。

编辑HelloWorld/server.py

from flask import Flask, url_for, redirect

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'hello world'

@app.route('/test1')
def test1():
    print('this is test1')
    return redirect(url_for('test2'))

@app.route('/test2')
def test2():
    print('this is test2')
    return 'this is test2'

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

运行HelloWorld/server.py,在浏览器中访问http://127.0.0.1:5000/test1,浏览器的url会变成http://127.0.0.1:5000/test2,并显示:

this is test2

本节源码

源码


( 本文完 )