基础用法,没有参数:
@app.route('/HelloWorld')
def hello_world():
return "Hello World!"
带有参数的使用 :
@app.route('/parames/<username>/')
def hello_world3(username, age=20):
return username + ''
以上代表的是路径参数。
Flask中的参数:
1)都是关键字参数
2)默认标识是<>
3)username需要和对应的视图函数的参数名字保持一致。
4)参数允许有默认值:
如果有默认值,那么在路由中,不传输参数也是可以的。
如果没有默认值,参数在路由中必修传递。
5)参数默认类型是string,如果想修改为其它类型,如下
<参数类型:username>
# 设置username为int类型
<string:username>
1.普通类型:
- string 默认类型,会将斜线认为是参数分隔符
- int 限制参数的类型是int类型
- float 显示参数对的类型是float类型
- path 接受到的数据格式是字符串,特性会将斜线认为是一个字符
2.path类型使用:
@app.route('/usepath/<path:name>/', methods=['GET', 'POST'])
def use_path(name):
return str(name)
userpath后面的路径随便写,如:http://127.0.0.1:5000/usepath/dfdsf/dsfsdf/fdsfds/,
3.uuid 类型使用:
@app.route('/getuuid/')
def get_uuid():
# d01d1bd6-cb22-4d64-89d5-830928ba5842
return str(uuid.uuid4())
@app.route('/useuuid/<uuid:name>/')
def use_uuid(name):
print("uuid是:",name)
return '获取到了uuid'
则路径中的参数必须是UUID类型的
http://127.0.0.1:5000/useuuid/d01d1bd6-cb22-4d64-89d5-830928ba5842
4.any类型:
any 任意一个,列出的元组中的任意一个,和枚举一个意思
@app.route('/any/<any(a,b,c):an>/')
def useany(an):
return str(an)
使用any只能使用指定的参数,如上面只能用a,b,c,这三个参数。
http://127.0.0.1:5000/any/b
史上超详细的Flask路径参数以及请求参数讲解 - 简书