Flask路由系统 򃗾

Posted bbb001

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask路由系统 򃗾相关的知识,希望对你有一定的参考价值。

原文: http://blog.gqylpy.com/gqy/337

"@(Flask路由)
***

动态路由参数

三种用法

  1. <int:xx> 要求输入的url必须是可转换为int类型的
  2. <string:xx> 要求输入的url必须是可转换为String类型
  3. <xx> 默认使用的是可转换为String类型的

开始测试

代码如下:

from flask import Flask

app = Flask(__name__)

# @app.route('/test/<int:xx>')  # int:要求输入的url必须是可转换为int类型的
# @app.route('/test/<string:xx>')  # string:要求输入的url必须是可转换为String类型
@app.route('/test/<xx>')  # 默认是可转换为String类型的
def test(xx):  # 别忘了接收路由参数
    print(xx)
    return f'xx'  # Python3.6新特性,见下面的解释

app.run(debug=True)


# Python3.6新特性:
a = 1
print(f'a')  # 打印结果:1

浏览器访问:
技术图片
***

路由参数

methods

用于重新定义允许的请求,默认为GET

示例:

# 将允许"GET", "POST"请求:
@app.route('/test01', methods=['GET', 'POST'])
def test01():
    pass

endpoint

用于定义反向url地址,默认为视图函数名。

开始测试

代码如下:

from flask import Flask, url_for, redirect

app = Flask(__name__)

@app.route('/test02', endpoint='test2')  # endpoint='test2':定义url地址别名,默认为函数名(test02)
def test02():
    print(url_for('test2'))  # /test02
    return 'This is test02'


@app.route('/test03')
def test03():
    return redirect(url_for('test2'))  # 将跳转至test02页面


app.run(debug=True)

此时,浏览器访问 test03 页面,将跳转到 test02 页面。
***

defaults

用于定义视图函数的默认值(例如:id: 1)。

开始测试

代码如下:

@app.route('/test04', defaults='id': 1)
def test04(id):
    print(id)
    return f'The id is id.'

浏览器访问:
技术图片


strict_slashes

用于控制url地址结尾符:
值为True时:结尾不能是"/"
值为False时:无论结尾"/"是否存在,都可访问"/

示例代码

# @app.route('/test05', strict_slashes=False)
@app.route('/test05', strict_slashes=True)  # 此时url结尾不能是"/"
def test05():
    return 'test05'


redirect_to

用于url地址重定向
将直接跳转,连当前url的视图函数都不走

@app.route('/test06', redirect_to='/test07')  # redirect_to='/test07':将跳转至test07
def test06():
    return 'test06'


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

此时,浏览器访问 test06 页面,将直接跳转到 test07 页面。
***

subdomain

用于定义子域名前缀,同时还需要指定app.config[‘SERVER_NAME‘]的值

app.config['SERVER_NAME'] = 'zyk.com'  # ??

@app.route('/test08', subdomain='blog')  # ??
def test08():
    return "Welcome to zyk's blog"

app.run('0.0.0.0', 5000, debug=True)  # 使用域名时,必须指定监听的ip

# 访问地址为:blog.zyk.com/test08

"

原文: http://blog.gqylpy.com/gqy/337

以上是关于Flask路由系统 򃗾的主要内容,如果未能解决你的问题,请参考以下文章

Flask系列 路由系统

Flask--路由系统

Flask最强攻略 - 跟DragonFire学Flask - 第七篇 Flask 中路由系统

源码解析flask的路由系统

flask路由系统

Flask之路由系统