flask 路由
django路由
地址:https://www.cnblogs.com/gjjcode/articles/17399093.html
一. 路由参数
当使用多层装饰器的时候, 必须指定别名 endpoint, 否则 @app装饰器 装饰的是自定义装饰器的 inner 函数。 路由名则都是 inner 了,会报错。
@app.route(rule, methods, endpoint)
rule: 字符串的路径,使用转换器
'default': UnicodeConverter, # <name> 默认
'string': UnicodeConverter, # <string:name>
'any': AnyConverter, # 任何
'path': PathConverter, # /xx/sss/
'int': IntegerConverter, # <int:pk>
'float': FloatConverter, # 小数
'uuid': UUIDConverter, # asdfas-asdfas-asdf
methods: 列表,规定请求的方式,如果列表中没有,该请求方式不被支持,
eg: ['GET', 'POST']
endpoint:路由别名,如果不写,会以被装饰的函数名作为别名,django中叫name,
eg: endpoint = 'index'
二. 路由本质
1 本质
flask 中路由是使用装饰器的,但是它的本质其实是app对象 Flask 的方法 self.add_url_rule(rule, endpoint, f, **options)
如果在视图函数上加了装饰器,其实本质是在调用self.add_url_rule
# 1. @app.route('/') 中,route 源码如下:是一个装饰器。
@setupmethod
def route(self, rule, **options):
def decorator(f):
endpoint = options.pop("endpoint", None)
# add_url_rule
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
# 2. 加了装饰器最终,返回的还是index,只不过执行了 self.add_url_rule(rule, endpoint, f, **options)
# 3. Flask 类中得 add_url_rule 方法
-rule:就是装饰器传入的路径,路由
-endpoint:别名
-view_func:视图函数不加括号
# 4. 得到的结论,现在不需要使用装饰器来注册路由了,自己写。
# 其实跟djagno没有大的差距,只是使用装饰器来配置
app.add_url_rule('/home', view_func=home, endpoint='home')
2 add_url_rule的参数
2.1 @app.route 和 app.add_url_rule参数:
rule # URL规则
view_func, # 视图函数名称
defaults = None, # 默认值, 当URL中无参数,函数需要参数时,使用defaults = {'k': 'v'}, 为函数提供参数,就是djagno中得kwargs
endpoint = None, # 别名,用于反向生成URL,即: url_for('名称'),等同于 django 的 reverse
methods = None, # 允许的请求方式,如:["GET", "POST"]
2.2 严格匹配(strict_slashes)
@app.route('/index', strict_slashes=False)
访问 http://www.xx.com/index/
或 http://www.xx.com/index 均可
@app.route('/index', strict_slashes=True)
仅访问 http://www.xx.com/index
2.3 重定向(redirect_to)
redirect_to 默认值为 None
@app.route('/index/<int:nid>', redirect_to='/home/<nid>')