一行 @app.route(...) 之后,Flask 内部多了什么?它和 add_url_rule 是什么关系?endpoint 是怎么来的?这篇把这些一一打印出来。
源码:
1 | @app.route("/hello", methods=["GET"])
2 | def hello(): return "hi"
注册前 → 后:规则数 1 → 2 | view_functions 数 1 → 2
装饰器返回的是原函数: hello | callable: True | 类型: function
Rule 对象:rule = /hello | endpoint = hello | methods = ['GET', 'HEAD', 'OPTIONS'] | strict_slashes = True | view_functions["hello"] is hello: True下一篇:URL Rule 与路由匹配顺序。
@route 的规则 : [('/x', 'f', ['OPTIONS', 'POST'])]
add_url_rule : [('/x', 'f', ['OPTIONS', 'POST'])]
相同: True
Scaffold.route 里的 decorator(原样):
def decorator(f: T_route) -> T_route:
endpoint = options.pop("endpoint", None)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator两个同名函数 → AssertionError: View function mapping is overwriting an existing endpoint function: view 自定义 endpoint 后 view_functions 的键: ['c_custom', 'static', 'view']
/one → ['GET', 'HEAD', 'OPTIONS']
/three → ['OPTIONS', 'POST']
/two → ['GET', 'HEAD', 'OPTIONS']
请求: {'/one': 200, '/two': 200, '/three': 405} | POST /three: 200AssertionError: The setup method 'get' can no longer be called on the application. It has already handled its first request, any changes will not be applied consistently.
Endpoint Methods Rule -------- --------- ----------------------- items GET, POST /items static GET /static/<path:filename> user GET /users/<int:uid>