加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

【Flask路由系统】_

发布时间:2020-12-20 11:02:05 所属栏目:Python 来源:网络整理
导读:目录 动态路由参数 路由参数 methods endpoint defaults strict_slashes redirect_to subdomain 原文: http://106.13.73.98/__/112/ @(Flask路由) *** 动态路由参数 三种用法 int:xx 要求输入的url必须是可转换为int类型的 string:xx 要求输入的url必须是可

目录

  • 动态路由参数
  • 路由参数
    • methods
    • endpoint
    • defaults
    • strict_slashes
    • redirect_to
    • subdomain

原文: http://106.13.73.98/__/112/

@(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://106.13.73.98/__/112/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读