flask add_url_rule的使用
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的使用的更多相关文章
- Flask——route
Flask——route 关于路由flask中有三种方法(例子)处理: flask.Flask.route 装饰器(关于装饰器可以参考该文),这时最常见的使用方法,在装饰器的参数中加入想要的路由即可, ...
- Flask路由与蓝图Blueprint
需求分析: 当一个庞大的系统中有很多小模块,在分配路由的时候怎么处理呢?全部都堆到一个py程序中,调用@app.route? 显然这是很不明智的,因为当有几十个模块需要写路由的时候,这样程序员写着写着 ...
- python框架之Flask(2)-路由和视图&Session
路由和视图 这一波主要是通过看源码加深对 Flask 中路由和视图的了解,可以先回顾一下装饰器的知识:[装饰器函数与进阶] 路由设置的两种方式 # 示例代码 from flask import Fla ...
- 欢迎来到 Flask 的世界
欢迎来到 Flask 的世界 欢迎阅读 Flask 的文档.本文档分成几个部分,我推荐您先读 < 安装 >,然后读< 快速上手 >.< 教程 > 比快速上手文档更详 ...
- Python Web Flask源码解读(二)——路由原理
关于我 一个有思想的程序猿,终身学习实践者,目前在一个创业团队任team lead,技术栈涉及Android.Python.Java和Go,这个也是我们团队的主要技术栈. Github:https:/ ...
- Flask 笔记
1.CBV 模式 1.继承 views.MethodView from flask.views import MethodView 2.HTTP具有 8 种请求方法 - CBV中的方法 - GET 获 ...
- flask中的g、add_url_rule、send_from_directory、static_url_path、static_folder的用法
Flask中的g对象是个很好的东西,主要用于在一个请求的过程中共享数据.可以随意给g对象添加属性来保存数据,非常的方便,下面的代码是一个使用g对象的例子.下面的这个例子会使用random随机产生一个0 ...
- flask中Flask()和Blueprint() flask中的g、add_url_rule、send_from_directory、static_url_path、static_folder的用法
1.Blueprint()在蓝本注册函数register_blueprint()中,第一个参数为所注册的蓝本名称.当我们在应用对象上注册一个蓝图时,需要指定一个url_prefix关键字 参数(这个参 ...
- 8、Flask实战第8天:add_url_rule和app.route原理
之前我们使用@app.route这个装饰器来把视图函数和url绑定 @app.route('/') def hell_world(): return 'hello world' 而且我们可以通过url ...
随机推荐
- 题解 [SCOI2007]修车
题面 解析 这题要拆点.. 首先,证明一个式子: 设修理员M修了N辆车, 且修每辆车的时间为W1,W2....WN. 那么,这个修理员一共花的时间就为:W1*N+W2*(N-1)+...+WN*1. ...
- 设置Portainer管理Docker并且开启https(简单方法)
1. 序言 Portainer是一个十分好用的docker图形化管理界面,可以很方便的查看容器状态,错误log等等. 2. 安装 安装portainer是十分简单的,只需要执行docker pull ...
- LCA离线Tarjan,树上倍增入门题
离线Tarjian,来个JVxie大佬博客最近公共祖先LCA(Tarjan算法)的思考和算法实现,还有zhouzhendong大佬的LCA算法解析-Tarjan&倍增&RMQ(其实你们 ...
- USACO19JAN Redistricting
题目链接:戳我 一个优先队列优化DP 一定要注意第二关键字的排序啊!!我真的是菜,被坑了好久qwq 设\(f[i]\)表示前i个的最小答案,从前面选择的时候第一关键字是f[j]的大小,第二关键字是要确 ...
- nginx 入门实战
nginx入门实战 nginx 安装与卸载 下载安装 进入 http://nginx.org/en/download.html 下载自己想要的版本,我选择的stable版本 tar -zxvf ngi ...
- php 解析json失败,解析为空,json在线解析器可以解析,但是json_decode()解析失败(原)
$str2='{"code":200,"datas":{"id":1,"coupon_id":"123&quo ...
- webpack搭建多页面系统(一):对webpack 构建工具的理解
为什么使用webpack构建工具? 1.开发效率方面: 在一般的开发过程中,分发好任务后,每个人完成自己单独的页面,如果有的人开发完成之后,接手别人的任务,就有可能造成开发时候的冲突. 如果利用模块化 ...
- idea 远程代码调试
声明一点:重要的事情说3遍 本地代码和服务器代码必须一致 本地代码和服务器代码必须一致 本地代码和服务器代码必须一致 第一步,创建remote 第二步.填写服务器信息 第三部.tomcat/bin/s ...
- LeetCode 143. 重排链表(Reorder List)
题目描述 给定一个单链表 L:L0→L1→…→Ln-1→Ln , 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→… 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换. ...
- 黑马vue---10-11、Vue实现跑马灯效果
黑马vue---10-11.Vue实现跑马灯效果 一.总结 一句话总结: 1. 给 [浪起来] 按钮,绑定一个点击事件 v-on @ 2. 在按钮的事件处理函数中,写相关的业务逻辑代码:拿到 ...