flask 路由

1.一般  

http://127.0.0.1:5000/meng

@app.route('/hello')
def hello_world():

    return 'heeee'

2.类型转换

默认接受转成string类型

http://127.0.0.1:5000/3

@app.route('/<int:count>')
def index(user):
    return str(type(user))

可转换的其他类型

 

string

(缺省值) 接受任何不包含斜杠的文本

int

接受正整数

float

接受正浮点数

path

类似 string ,但可以包含斜杠

uuid

接受 UUID 字符串

3.传递多个值 

@app.route('/<user>/<int:count>')
def index(user,count):
    return count

 

 4.默认值

@app.route('/user', defaults={'count': 20})
@app.route('/user/<int:count>')
def index(count):
    return str(count)

 

 

5.参数限制

@app.route('/<any(blue,red):color>')
def index(color):
    print(color)
    return color

http://127.0.0.1:5000/red  如果url里对应的位置,不是blue或red就会报404

 

6.请求方式

from flask import Flask,request

app = Flask(__name__)

@app.route('/<user>', methods=['get','post','put'])
def index(user):
    print(request.method)
    if request.method == 'GET': #要大写
        return user + 'Get'
    elif request.method == 'POST':
        return user + 'Post'
    else:
        return user + request.method

 

1

GET

以未加密的形式将数据发送到服务器。最常见的方法。

2

HEAD

和GET方法相同,但没有响应体。

3

POST

用于将HTML表单数据发送到服务器。POST方法接收的数据不由服务器缓存。

4

PUT

用上传的内容替换目标资源的所有当前表示。

5

DELETE

删除由URL给出的目标资源的所有当前表示。

7.末尾是否加 /

@app.route('/hello/')

加了/的话

http://127.0.0.1:5000/hello/

http://127.0.0.1:5000/hello

都能访问

 

 

8. key-value方式传值

http://127.0.0.1:5000?user=meng

from flask import Flask,request

app = Flask(__name__)

@app.route('/')
def index():
    user = request.args.get("user")
    return user

 

原文地址:https://www.cnblogs.com/buchizaodian/p/11142548.html