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. 坚果Pro2刷魔趣系统教程,刷回锤子系统教程

    一.刷魔趣系统 1.高通驱动安装 https://blog.csdn.net/qq_43653944/article/details/86702169 2.刷入twrp rec https://blo ...

  2. Neko does Maths CodeForces - 1152C 数论欧几里得

    Neko does MathsCodeForces - 1152C 题目大意:给两个正整数a,b,找到一个非负整数k使得,a+k和b+k的最小公倍数最小,如果有多个k使得最小公倍数最小的话,输出最小的 ...

  3. npm脚本编译代码

    echo offset codeUrl=D:\svn\oppo_mis\OCSS_NEW\Branches\ProjectCode20190909\h5_ocssset publishUrl=D:\P ...

  4. Java集合框架之接口Collection源码分析

    本文我们主要学习Java集合框架的根接口Collection,通过本文我们可以进一步了解Collection的属性及提供的方法.在介绍Collection接口之前我们不得不先学习一下Iterable, ...

  5. Apache Ranger && HDFS

    Apache Ranger && HDFS 标签(空格分隔): Hadoop HDFS HDFS对于任何Hadoop大数据平台来说都是核心组成部分,为了加强对Hadoop平台的数据保护 ...

  6. Java并发编程(十一)——原子操作CAS

    一.原子操作 syn基于阻塞的锁的机制,1.被阻塞的线程优先级很高,2.拿到锁的线程一直不释放锁怎么办?3.大量的竞争,消耗cpu,同时带来死锁或者其他安全. CAS的原理 CAS(Compare A ...

  7. Linux 多线程按照线程顺序打印字符

    #include <stdio.h> #include <pthread.h> #include <unistd.h> ; pthread_mutex_t mute ...

  8. IDEA问题java: -source 1.6 中不支持diamond、 lambda 表达式

    文章目录 一.问题:连片的java: -source 1.6 中不支持 diamond 运算符.lambda 表达式 二.解决方法: 1.在微信群里问大佬,大佬在玩游戏,回复的比较慢 2.自己查Goo ...

  9. Linux安全工具之fail2ban防爆力破解

    一:简单介绍 fail2ban是一款实用软件,可以监视你的系统日志,然后匹配日志的错误信息(正则式匹配)执行相应的屏蔽动作 在企业中,有些很多人会开放root登录,这样就有机会给黑客造成暴力破解的机会 ...

  10. Windows 全绿色安装Mysql

    1.从Oracle官网上下载Mysql的Windows安装包,注意要下载Zip文件 2.将Mysql的Zip文件下载到本地电脑指定目录下 3.配置my.inia. 在<安装目录>下创建一个 ...