Flask中路由参数

Flask中路由参数、请求方式设置

一、参数设置

1.参数类型

Flask中参数的使用

@app.route('/parames/<username>/')
def hello_world3(username, age=20):
    return username + ''

以上代表的是路径参数。

Flask中的参数:
1)都是关键字参数 
2)默认标识是<>
3)username需要和对应的视图函数的参数名字保持一致。
4)参数允许有默认值:
如果有默认值,那么在路由中,不传输参数也是可以的。
如果没有默认值,参数在路由中必修传递。
5)参数默认类型是string,如果想修改为其它类型,如下
<参数类型:username>

# 设置username为int类型
<int:username> 

参数语法

  • string 默认类型,会将斜线认为是参数分隔符
  • int 限制参数的类型是int类型
  • float 显示参数对的类型是float类型
  • path 接受到的数据格式是字符串,特性会将斜线认为是一个字符

2.未指定参数类型

在url中传入参数时,如果没有指定参数的类型,会默认为参数是string类型。
如下:
没有给id指定参数类型,id默认是string类型,想要对id做运算,就必须先转化成int类型,最后返回的内容必须是字符串,所以再转成string类型。

@house_blueprint.route('/<id>/')
def h(id):
    id = int(id) ** 5
    id = str(id)
    return id

运行结果:

 

3.指定参数类型

(1)int、float类型

给参数指定类型,就在参数前加上参数类型和冒号即可。如下,指定id是int类型,可以直接进行运算。

@house_blueprint.route('/<int:id>/')
def h(id):
    id = id ** 5
    id = str(id)
    return id
运行结果:
 

(2)path类型

指定path类型,可以获取当前路径,值得注意的是获取的不是完整路径,只是此处传入的路径参数,如下获取的路径是 testpath/test。

@house_blueprint.route('/<path:url_path>/')  #蓝图
def h(url_path):
    return 'path:%s' % url_path

运行结果:
 
@app.route('/usepath/<path:name>/', methods=['GET', 'POST'])
def use_path(name):
    return str(name)

userpath后面的路径随便写,如

http://192.168.100.95:8080/usepath/dfdsf/dsfsdf/fdsfds/
http://192.168.100.95:8080/usepath/dfdsf/

(3)uuid类型

@house_blueprint.route('/<uuid:uu>')
def h(uu):
    return 'uu:s' % uu

(4) any:可以指定多种路径,这个通过一个例子来进行说明:

 

@app.route('/index/<any(article,blog):url_path>/')
def item(url_path):
return url_path

以上例子中,item这个函数可以接受两个URL,一个是http://127.0.0.1:5000/index/article/,另一个是http://127.0.0.1:5000/index//blog/。并且,一定要传url_path参数,当然这个url_path的名称可以随便。

请求方法
常用的有5中,请求方式默认是GET,可以在路由中设置,如下

methods=['GET', 'POST','DELETE'.'PUT','HEAD']

二、请求方式设置

flask中请求默认是get请求,若想要指定其他请求方式,用参数methods指定。如用户注册时,需要把用户填写的数据存入数据库,生成一条新用户的记录,此处就需要用到post请求。

@house_blueprint.route('/register/', methods=['POST'])
def register():
    register_dict = request.form
    username = register_dict['usrename']
    password = register_dict.get('password')
    
    user = User()
    user.username = username
    user.password = password
    db.session.add(user)
    db.session.commit()

    return '创建用户成功'
https://www.jianshu.com/p/e1b7d85efccb
原文地址:https://www.cnblogs.com/leijiangtao/p/11758329.html