from flask import Flask,url_for
#url_for 接受两个参数(endpoint,**value)endpoint没有指定就是默认的函数名,根据 view_func.__name__ app = Flask(__name__) @app.route('/')
def hello_world():
return "Hello World!" #url注册的另一种方式
def my_list():
return '我是列表页' app.add_url_rule('/list/',endpoint='my_list',view_func=my_list) # 这里endpoint可以不填 ,view_func 一定要是函数名:具体看下面源码解释 #请求上下文
with app.test_request_context():
pass if __name__ == '__main__':
app.run(debug=True)

route的源码分析,解释url_for 和 add_url_rule的使用

def route(self, rule, **options):
#先看下,route有几个参数,三个参数,对象,就是 app = Flask(__name__),rule 就是你注册的url '/',
**options可变长参数,能接受(字典,关键字参数:endpoint='index')
"""A decorator that is used to register a view function for a given URL rule. This does the same thing as :meth:`add_url_rule` but is intended for decorator usage:: @app.route('/') def index(): return 'Hello World' For more information refer to :ref:`url-route-registrations`. :param rule: the URL rule as string :param endpoint: the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint :param options: the options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (``GET``, ``POST`` etc.). By default a rule just listens for ``GET`` (and implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is implicitly added and handled by the standard request handling. """ 

def decorator(f): 
  #f = 相当于你装饰的函数内存对象:hello_world
  endpoint = options.pop('endpoint', None) #options就是字典对象,用pop方法,如果你route()没有传递endpoint,就是None
  self.add_url_rule(rule, endpoint, f, **options) #主要是调用这个方法装饰器还是执行了app.add_url_rule,把‘/’,None,hello_world 传来进去
  return f 

return decorator

看下 add_url_rule干了什么事

    def add_url_rule(self, rule, endpoint=None, view_func=None,
provide_automatic_options=None, **options):
    #rule='/',endpoint = None ,view_func = hello_world
"""Connects a URL rule. Works exactly like the :meth:`route`
decorator. If a view_func is provided it will be registered with the
endpoint. Basically this example:: @app.route('/')
def index():
pass Is equivalent to the following:: def index():
pass
app.add_url_rule('/', 'index', index) If the view_func is not provided you will need to connect the endpoint
to a view function like so:: app.view_functions['index'] = index Internally :meth:`route` invokes :meth:`add_url_rule` so if you want
to customize the behavior via subclassing you only need to change
this method. For more information refer to :ref:`url-route-registrations`. .. versionchanged:: 0.2
`view_func` parameter added. .. versionchanged:: 0.6
``OPTIONS`` is added automatically as method. :param rule: the URL rule as string
:param endpoint: the endpoint for the registered URL rule. Flask
itself assumes the name of the view function as
endpoint
:param view_func: the function to call when serving a request to the
provided endpoint
:param provide_automatic_options: controls whether the ``OPTIONS``
method should be added automatically. This can also be controlled
by setting the ``view_func.provide_automatic_options = False``
before adding the rule.
:param options: the options to be forwarded to the underlying
:class:`~werkzeug.routing.Rule` object. A change
to Werkzeug is handling of method options. methods
is a list of methods this rule should be limited
to (``GET``, ``POST`` etc.). By default a rule
just listens for ``GET`` (and implicitly ``HEAD``).
Starting with Flask 0.6, ``OPTIONS`` is implicitly
added and handled by the standard request handling.
"""
if endpoint is None:
endpoint = _endpoint_from_view_func(view_func) #view_func = hello_world ,看下源码返回函数的名字
options['endpoint'] = endpoint
methods = options.pop('methods', None) # if the methods are not given and the view_func object knows its
# methods we can use that instead. If neither exists, we go with
# a tuple of only ``GET`` as default.
if methods is None:
methods = getattr(view_func, 'methods', None) or ('GET',)
if isinstance(methods, string_types):
raise TypeError('Allowed methods have to be iterables of strings, '
'for example: @app.route(..., methods=["POST"])')
methods = set(item.upper() for item in methods) # Methods that should always be added
required_methods = set(getattr(view_func, 'required_methods', ())) # starting with Flask 0.8 the view_func object can disable and
# force-enable the automatic options handling.
if provide_automatic_options is None:
provide_automatic_options = getattr(view_func,
'provide_automatic_options', None) if provide_automatic_options is None:
if 'OPTIONS' not in methods:
provide_automatic_options = True
required_methods.add('OPTIONS')
else:
provide_automatic_options = False # Add the required methods now.
methods |= required_methods 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: #view_func = hello_world
old_func = self.view_functions.get(endpoint) #view_functions = {}
if old_func is not None and old_func != view_func:
raise AssertionError('View function mapping is overwriting an '
'existing endpoint function: %s' % endpoint)
self.view_functions[endpoint] = view_func #把endpoint=hello_world 添加到 view_functions 字典中。防止重命名

flask add_url_rule的使用的更多相关文章

  1. Flask——route

    Flask——route 关于路由flask中有三种方法(例子)处理: flask.Flask.route 装饰器(关于装饰器可以参考该文),这时最常见的使用方法,在装饰器的参数中加入想要的路由即可, ...

  2. Flask路由与蓝图Blueprint

    需求分析: 当一个庞大的系统中有很多小模块,在分配路由的时候怎么处理呢?全部都堆到一个py程序中,调用@app.route? 显然这是很不明智的,因为当有几十个模块需要写路由的时候,这样程序员写着写着 ...

  3. python框架之Flask(2)-路由和视图&Session

    路由和视图 这一波主要是通过看源码加深对 Flask 中路由和视图的了解,可以先回顾一下装饰器的知识:[装饰器函数与进阶] 路由设置的两种方式 # 示例代码 from flask import Fla ...

  4. 欢迎来到 Flask 的世界

    欢迎来到 Flask 的世界 欢迎阅读 Flask 的文档.本文档分成几个部分,我推荐您先读 < 安装 >,然后读< 快速上手 >.< 教程 > 比快速上手文档更详 ...

  5. Python Web Flask源码解读(二)——路由原理

    关于我 一个有思想的程序猿,终身学习实践者,目前在一个创业团队任team lead,技术栈涉及Android.Python.Java和Go,这个也是我们团队的主要技术栈. Github:https:/ ...

  6. Flask 笔记

    1.CBV 模式 1.继承 views.MethodView from flask.views import MethodView 2.HTTP具有 8 种请求方法 - CBV中的方法 - GET 获 ...

  7. flask中的g、add_url_rule、send_from_directory、static_url_path、static_folder的用法

    Flask中的g对象是个很好的东西,主要用于在一个请求的过程中共享数据.可以随意给g对象添加属性来保存数据,非常的方便,下面的代码是一个使用g对象的例子.下面的这个例子会使用random随机产生一个0 ...

  8. flask中Flask()和Blueprint() flask中的g、add_url_rule、send_from_directory、static_url_path、static_folder的用法

    1.Blueprint()在蓝本注册函数register_blueprint()中,第一个参数为所注册的蓝本名称.当我们在应用对象上注册一个蓝图时,需要指定一个url_prefix关键字 参数(这个参 ...

  9. 8、Flask实战第8天:add_url_rule和app.route原理

    之前我们使用@app.route这个装饰器来把视图函数和url绑定 @app.route('/') def hell_world(): return 'hello world' 而且我们可以通过url ...

随机推荐

  1. [Git] How to revert one file changes from one commit

    Many times we might changed one file which we don't intent to do... but it was too late, until we fo ...

  2. 洛谷p2375 kmp

    题意 给你一个字符串,让你求一个\(num\)数组,\(num[i]\)为长度为\(i\)的前缀的公共前后缀长度不超过\(\lfloor \frac{i}{2}\rfloor\)的个数, 例如&quo ...

  3. canvas小实验

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. AcWing:109. 天才ACM(倍增 + 归并排序)

    给定一个整数 MM,对于任意一个整数集合 SS,定义“校验值”如下: 从集合 SS 中取出 MM 对数(即 2∗M2∗M 个数,不能重复使用集合中的数,如果 SS 中的整数不够 MM 对,则取到不能取 ...

  5. E. Compress Words(Hash,KMP)

    E. Compress Words time limit per test 1 second memory limit per test 256 megabytes input standard in ...

  6. html基础(img、a、列表 )

    图片标签(img) <img src="图片路径" alt="图片描述 图片无法正常显示出现文字" title="爱你"/> i ...

  7. 12.数值的整数次方 Java

    题目描述 给定一个double类型的浮点数base和int类型的整数exponent.求base的exponent次方. 这道题看似简单,其实BUG重重.要注意的问题: 1 关于次幂的问题特殊的情况, ...

  8. git一键push至github脚本

    ######################################################################### # File Name: push.sh # Aut ...

  9. 在Linux上部署Nginx,反向代理tornado的WebSite

    1.安装 Nginx yum install -y nginx 2. 修改nginx配置文件 cd /etc/nginx/ mv nginx.conf nginx.conf.swf mv nginx. ...

  10. SSD 页、块、垃圾回收

    基本操作: 读出.写入.擦除: 因为NAND闪存单元的组织结构限制,单独读写一个闪存单元是不可能的.存储单元被组织起来并有着十分特别的属性.要知道这些属性对于为固态硬盘优化数据结构的过程和理解其行为来 ...