Flask_动态URL参数类型
一.类型介绍
如果需要指定类型,则要写成 converter:variable ,其中 converter 就是类型名称,可以有以下几种:
-
string
如果没有指定具体的数据类型,那么默认就是使用
string
数据类型。 -
int
数据类型只能传递
int
类型。 -
float
数据类型只能传递
float
类型。 -
path
数据类型和
string
有点类似,都是可以接收任意的字符串,但是path
可以接收路径,也就 是说可以包含斜杠。 -
uuid
数据类型只能接收符合
uuid
的字符串。uuid
是一个全宇宙都唯一的字符串,一般可以用来 作为表的主键。获取uuid方法:
import uuid uuid.uuid4()
-
any
数据类型可以在一个
url
中指定多个路径。
注意:若是数据与设置的类型不能匹配,则会返回 Not Found
二.实例
#coding=utf-8
from flask import Flask
app = Flask(__name__)
@app.route('/str/<id>')
def r_str(id):
print(f'接收到了{id}文章')
print(type(id))
return f'返回{id}的文章'
@app.route('/int/<int:id>')
def r_int(id):
print(f'接收到了{id}文章')
print(type(id))
return f'返回{id}的文章'
@app.route('/float/<float:id>')
def r_float(id):
print(f'接收到了{id}文章')
print(type(id))
return f'返回{id}的文章'
@app.route('/path/<path:id>')
def r_path(id):
print(f'接收到了{id}文章')
print(type(id))
return f'返回{id}的文章'
@app.route('/uuid/<uuid:id>')
def r_uuid(id):
print(f'接收到了{id}文章')
print(type(id))
return f'返回{id}的文章'
@app.route('/<any(user,item):tmp>/<int:id>')
def r_any(tmp,id):
if tmp == 'user':
print(f'接收到了{id}用户信息')
return f'返回了id为{id}的用户信息'
elif tmp == 'item':
print(f'接收到了{id}元素信息')
return f'返回了id为{id}的元素信息'
if __name__ == '__main__':
app.run(debug=True)
注:
如果觉得笔记有些问题,麻烦在百忙之中在评论中指正,或提出建议!另外,如果觉得这份笔记对你有所帮助,麻烦动动发财的小手手点一波赞!