Flask内置URL变量转换器 --

 

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)





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