url传递参数
url传递参数
一、传递参数的语法是:/<参数名>/
,然后在视图函数也要定义同名的参数。
@app.route('/b/<url_path>/')
def show_p_path(url_path):
return 'the url_path value is %s' %url_path
注意两点:
1、视图函数也要定义同名的参数。
2、该参数默认为string类型
二、为参数指定数据类型
string:默认数据类型,不接受'/'。
int :接受整形
float :接受浮点类型
path:和string类似,接受斜杠'/'
uuid: 只能接收uuid格式的字符串,并且全球唯一 。
any:any数据类型和可以在一个url中指定多个路径,
1、int float string类型示例讲解:
@app.route('/p1/<int:url_path>/')
def show_p1_path(url_path):
return 'the url_path value is %s' %url_path
示例:
参数必须是整形,否则会报错:
2、path类型讲解,path类型与string类型之前的异同
@app.route('/p2/<path:url_path>/')
def show_p2_path(url_path):
return 'the url_path value is %s' %url_path
注意:string只可以接收一个路径,不可以接收斜杠'/'。path可接收多个路径,可以接受斜杠'/'。
示例:
3、uuid类型讲解
获取一个示例uuid的方式:
import uuid
print(uuid.uuid4())
@app.route('/p3/<uuid:url_path>/')
def show_p3_path(url_path):
return 'the url_path value is %s' %url_path
注意:uuid类型的id全宇宙唯一,并且有自己特定的编码方式。例如:2bebccb6-12fc-459d-ad32-e8995fbc24b1
缺点是,uuid太长。
4、any类型讲解
语法格式为:/<any(value1,value2):key>/
根据用户输入的value值确定key的值。示例如下:
@app.route('/p4/<any(blog,user):url_path>/<ID>/')
def show_p4_path(url_path,ID):
if url_path =='blog':
return 'the blog is %s' % ID
else:
return 'the user is %s' % ID
若用户在url中输入的是/p4/blog/.../
,url_path 将取blog为值。若用户输入的是 /p4/user/.../
url_path 将取user为值。
示例:
any数据类型可以在一个url中指定多个路径。
三、查询字符串方法接收用传递的参数
通过?key=value
形式传递。
@app.route('/d/')
def d():
wd = request.args.get('wd')
return 'the wd is %s' % wd
版权协议须知!
本篇文章来源于 岳岳 ,如本文章侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意
1359 0 2020-11-21