Python武器库开发-flask篇之URL重定向(二十三)

flask篇之URL重定向(二十三)

通过url_for()函数构造动态的URL:

我们在flask之中不仅仅是可以匹配静态的URL,还可以通过url_for()这个函数构造动态的URL

python 复制代码
from flask import Flask
from flask import url_for

app = Flask(__name__)

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

@app.route('/b')
def add():
    return "1+1=2"

@app.route('/user/<username>')
def user_index(username):
    return 'Hello {}'.format(username)
@app.route('/post/<int:post_id>')
def show_post(post_id):
    return 'Post {}'.format(post_id)
@app.route('/test')
def test():
    print(url_for('index'))
    print(url_for('user_index', username="Wang Gang"))
    print(url_for("show_post", post_id=1))
    return 'test'
if __name__ == '__main__':
    app.run(debug=True)

保存代码,然后我们去运行这个脚本

python 复制代码
python3 app.py

通过任意浏览器输入http://127.0.0.1:5000/test,获得相应的页面

此时相应的函数也被打印出来了

URL重定向:

现在我们来解读一下这段代码,首先我们定义了一个index()函数,作用是返回一个Hello World的界面

python 复制代码
#!/usr/bin/env python3

from flask import Flask
from flask import url_for
from flask import redirect

app = Flask(__name__)

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

@app.route('/<username>')
def hello(username):
    if username == 'handsome Wanggang':
        return 'Hello {}'.format(username)
    else:
    		#重定向到index这个函数
        return redirect(url_for("index"))
if __name__ == '__main__':
    app.run(debug=True)

然后我们定义了一个hello函数,在路由这块传入的参数如果是 handsome Wanggang,那么将返回相应的界面Hello handsome Wanggang,然如果传入的实参不是handsome Wanggang,而是其他的参数,那么将通过redirect这个函数和url_for()函数重定向到我们之前定义的index函数,输出 Hello World!

保存代码,然后我们去运行这个脚本

python 复制代码
python3 app.py

通过任意浏览器输入http://127.0.0.1:5000/handsome Wanggang,获得相应的页面

但是如果我们此时传入的参数是其他的参数,比如http://127.0.0.1:5000/Xiao Ming 或者是 http://127.0.0.1:5000/123 ,则URL将被重定向到index函数,输出Hello World!


相关推荐
databook1 天前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室1 天前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三1 天前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427111 天前
Python之语言特点
python
刘立军1 天前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python
这里有鱼汤2 天前
小白必看:QMT里的miniQMT入门教程
后端·python