码迷,mamicode.com
首页 > Web开发 > 详细

Flask内置URL变量转换器

时间:2019-02-16 00:08:30      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:any   eal   pre   inf   .com   back   route   执行   img   

 

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变量转换器

标签:any   eal   pre   inf   .com   back   route   执行   img   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!