Flask路由和视图
一、 路由系统
1. 路由系统基础
-
路由装饰器:
-
Flask使用装饰器
@app.route
来将URL规则绑定到视图函数上。 -
装饰器可以指定路径规则(
rule
)、请求方法(methods
)、以及别名(endpoint
)等。
-
-
转换器:
-
Flask默认支持多种路径转换器,如
int
、float
、string
等,用于将URL中的变量部分转换为不同的数据类型。 -
转换器使得URL可以动态匹配,并允许开发者定义复杂的URL规则。
-
DEFAULT_CONVERTERS = { 'default': UnicodeConverter, 'string': UnicodeConverter, 'any': AnyConverter, 'path': PathConverter, 'int': IntegerConverter, 'float': FloatConverter, 'uuid': UUIDConverter, }
-
2. 执行流程分析
-
路由装饰器:
-
@app.route
是一个装饰器,使用它来将一个函数绑定到一个URL规则上。 -
当装饰器被触发时,它实际上执行了
index = decorator(index)
,其中decorator
是route
方法返回的内部函数。 -
decorator
函数是route
方法的内部函数,它接收视图函数f
作为参数,并使用add_url_rule
方法将视图函数注册到路由上。 -
def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: def decorator(f: T_route) -> T_route: endpoint = options.pop("endpoint", None) self.add_url_rule(rule, endpoint,</
-