在 Flask 应用开发中,使用最多的一个方法可能就是 route() 了,它可以将一个URL地址与一个 view 函数绑定,当用户访问 URL 时,就会调用与其绑定了的 view 函数,而其 view 函数的处理结果将返回给浏览器,我们最常使用的方法如下面这样的:

from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Index Page'
if __name__ == '__main__':
app.run()

运行上面的代码,我们将可以使用访问 http://127.0.0.1:5000 ,页面返回“Index Page”,这整个过程是下面这样的:

Flask应用 app 有 route() 这个方法,代码如下:

 def route(self, rule, **options):
def decorator(f):
self.add_url_rule(rule, None, f, **options)
return f
return decorator

当我们启动 app 之后,app 首先会调用该方法,它会将其下一行所定义的函数作为参数传递给route() 方法,@route()@ 方法会运行 add_url_rule() 方法,将该函数绑定到一个 URL 规则上,接着返回该函数,整个过程是一个“函数注册”的过程,注册方法为 add_url_rule() 函数,接着我们再来看一下下 add_url_rule() 方法:

 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
if endpoint is None:
endpoint = _endpoint_from_view_func(view_func)
options['endpoint'] = endpoint
methods = options.pop('methods', None)
if methods is None:
methods = getattr(view_func, 'methods', None) or ('GET',)
provide_automatic_options = False
if 'OPTIONS' not in methods:
methods = tuple(methods) + ('OPTIONS',)
provide_automatic_options = True
options['defaults'] = options.get('defaults') or None
rule = self.url_rule_class(rule, methods=methods, **options)
rule.provide_automatic_options = provide_automatic_options
self.url_map.add(rule)
if view_func is not None:
self.view_functions[endpoint] = view_func

add_url_rule() 方法的运行流程如下:

  1. 检查 endpoint 参数是否为 None,如果为 None,则指定默认的 endpoint,这个我们一般都没有使用,所以就像我以前也都不知道有这么个参数
  2. 将 endpoint 加入到 options 参数中
  3. 如果未指定 methods ,则程序尝试去自动获取 methods 列表(这个 methods 是浏览器向服务器请求的方法列表,有 POST,GET,PUT 等)或者默认使用 GET 方法
  4. 如果 ‘OPTIONS’ 这项不在 methods 列表中,则将其加入
    获取“defaults”参数列表,这个是一个字典数据,比如 “defaults = {‘id’:1,‘title’=‘test’}”
  5. 根据参数创建 rule 对象。并将其添加到 app 的URL映射表中

通过上面的代码我们可以大概的知道一下下最开始那个添加应用路由的过程,那么我们其实也可以不使用默认的方法,而使用下面这样的方法来添加URL映射:

def index():
return 'Index Page'
app.add_url_rule('/',None,index)

这种方法可以让我们动态的添加URL映射:

def aha():
return 'Aha, Insight!'
@app.route('/')
def index():
app.add_url_rule('/aha', None, aha)
return 'Index Page'

运行上面的应用,访问 http://127.0.0.1:5000/aha 我们将得到错误页面:

Not Found
The requested URL was not found on the server.
If you entered the URL manually please check your spelling and try again.

因为这个URL还没有映射到我们的 app 中,也就不可能有相关的回调函数返回任何内容了,我们再运行访问一次“ http://127.0.0.1:5000 ”再返回去 http://127.0.0.1:5000/aha ,将得到“Aha, Insight!”的结果,这是因为当我们访问 http://127.0.0.1:5000/ 时,@index()@ 动态的添加了一个到 aha() 函数的映射。

Flask 的 url 映射都保存在一份叫作 url_map 的 werkzeug.routing.Map 对象中.

标签: none

评论已关闭