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!


相关推荐
charlie11451419112 分钟前
如何使用Qt创建一个浮在MainWindow上的滑动小Panel
开发语言·c++·qt·界面设计
孤狼warrior14 分钟前
灰色预测模型
人工智能·python·算法·数学建模
神仙别闹20 分钟前
基于Python实现LSTM对股票走势的预测
开发语言·python·lstm
机器学习之心1 小时前
小波增强型KAN网络 + SHAP可解释性分析(Pytorch实现)
人工智能·pytorch·python·kan网络
JavaEdge在掘金1 小时前
MySQL 8.0 的隐藏索引:索引管理的利器,还是性能陷阱?
python
站大爷IP1 小时前
Python办公自动化实战:手把手教你打造智能邮件发送工具
python
chao_7891 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
zdw2 小时前
fit parse解析佳明.fit 运动数据,模仿zwift数据展示
python
剑桥折刀s2 小时前
Python打卡:Day46
python
巴里巴气3 小时前
Python爬虫图片验证码和滑块验证码识别总结
爬虫·python