分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

Flask内置URL变量转换器

发布时间:2023-09-06 02:33责任编辑:顾先生关键词:暂无标签

Flask内置URL变量转换器:

转换器通过特定的规则执行,”<转换器: 变量名>”。<int: year>把year的值转换为证书,因此我们可以在视图函数中直接对year变量进行数学计算:

@app.route(‘/goback/<int:year>‘

def go_back(year):
    return ‘<p>Welcom to %s ! </p>‘ %(2019-year)

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

any转换器:

需要在转换器后添加括号来给出可选值,在写这个变量的值时,如果在可选值范围内,就会执行视图函数的逻辑,否则会报404错误

@app.route(‘/colors/<any(blue,white,red):color>‘)
def three_colors(color):
    return ‘<p>Love is patient and kind. Love is not jealous or boastful or proud or rude. </p>‘

if __name__ == ‘__main__‘:

    app.run(debug = True)

如果想再any转换器中传入一个预先定义好的列表,可以通过格式化字符串的方式(使用%或是format()函数)来否建URL规则字符串,例如:

colors = [‘blue‘,‘white‘,‘red‘]
@app.route(‘/colors/<any(%s):color>‘ %str((colors))[1:-1])
def three_clors(color):
    return ‘<p>Love is patient and kind. Love is not jealous or boastful or proud or rude. </p>‘

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



Flask内置URL变量转换器

原文地址:https://www.cnblogs.com/xiaxiaoxu/p/10386373.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved