Flask--路由

在Flask中路由是必不可少的。其实在所有的web框架中都有路由。

今天就聊一些Flask中的路由

首先路由是什么

@app.route('/index')
def index():
return render_template('index.html')

上面就是一个简单的路由。

接下来说一些路由中的参数

methods

当前 url 地址,允许访问的请求方式

@app.route('/index',methods=['GET', 'POST'])
def index():
return render_template('index.html')

当你不写 method 时。默认的是GET请求

endpoint

 反向url地址,默认为视图函数名 -- 类似于django的反相解析

from flask import url_for
@app.route('/index',methods=['GET', 'POST'],endpoint='index')
def index():
    return render_template('index.html')
@app.route('/home')
def home():
   print(url_for("index"))   # /index
return redirect('index')  # 不用担心 /index 路径改变
这样就可以通过别名进行重定向了。

defaults

视图函数的参数默认值

@app.route('/index',methods=['GET', 'POST'],defaults={'id':2})
def index(id):
    return render_template('index.html')

在使用 defaults 时。字典内的 key 在视图函数中必接收且形参的名字和字典的 key 一样。不然会报错

strict_slashes

是否严格遵循路由匹配规则 "/"

说白了。False : 无论结尾 "/" 是否存在均可以访问 , True : 结尾必须不能是 "/"

@app.route('/index',methods=['GET', 'POST'],strict_slashes=False)
def index():
    return render_template('index.html')

在不写 strict_slashes 时。默认是True

 

 

@app.route('/index',methods=['GET', 'POST'],strict_slashes=True)
def index():
    return render_template('index.html')

redirect_to 

url地址重定向

@app.route('/index',methods=['GET', 'POST'],strict_slashes=False,redirect_to='/login')
def index():
    return render_template('index.html')

在访问时。查看network,你会发现这样的现象

这个现象表示。redirect_to 是永久重定向,当访问 url 时。直接重定向。不会进视图函数 -- 301 / 308 都是重定向。随机出现

动态参数路由


@app.route('/index/<arg>/<int:num>',methods=['GET', 'POST'])
def index(arg,num):
print(arg)
print(num)
print(type(arg))
print(type(num))
return render_template('index.html')
动态参数用 <> 包裹 
<> 内可以写为 <int:num> 这样的话。参数必须是给int类型,不然会报错
<> 内不写的话,默认为str

 

最后在上一张图。助于记忆理解

 

posted @ 2019-07-11 17:04  __Invoker  阅读(165)  评论(0编辑  收藏  举报