Flask - 路由(route)
*1.什么是路由*
路由是处理 url 与视图函数关系的程序
**2.路由的体现**
在Flask中,路由是通过@app.route 装饰器来表示的
01.路由的基本体现
# 127.0.0.1:5000/
#localhost:5000/
@app.route('/')
return xxx
#127.0.0.1:5000/admin/login
@app.route('/admin/login')
return xxx
02.带参数的路由
参数在路由中是一个不确定的数据,根据访问时的路由向里传递
#127.0.0.1:5000/news/2018
#127.0.0.1:5000/news/2017
1.基本的带参路由
#127.0.0.1:5000/news/2018
#127.0.0.1:5000/news/2017
@app.route('/news/<year>')
def news(year):
year:表示的是地址栏上传递过来的数据
return xxx
2.带多个参数的路由
#127.0.0.1:5000/news/2018/7
#127.0.0.1:5000/news/2015/5
@app.route('/news/<year>/<month>')
def xxx(year,month):
return
3.指定参数类型的路由
#127.0.0.1:5000/info/xxx/20
#127.0.0.1:5000/info/xxx/25
@app.route('/info/<name>/<int:age>')
def info(name,age):
name :字符串
age :整数
return xxx
int:类型转换器
Flask 中所支持的类型转换器
类型转换器 作用
缺省 字符串,不能有斜杠(‘/’)
int: 整数
float: 小数
path: 字符串,可以有斜杠出现('/')
03.多URL的路由匹配
127.0.0.1:5000/
127.0.0.1:5000/index
实现方案;
@app.route('/地址1')
@app.route('/地址2')
......
def index():
xxx xxx
***3.URL 的反向解析***
正向解析:程序自动解析,根据@app.route()中的访问路径,来匹配
处理函数
反向解析:通过视图处理函数的名称生成对应的访问路径
在Flask 中实现反向解析
from flask import url_for
语法:
url_for(funName[,args])
funName:要生成地址的函数名
args:地址中需要的参数,可选的
返回值: 字符串,对应的访问地址