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 ...
随机推荐
- PC监听鼠标和键盘事件,定时无响应退出
直接上代码: window.onload = function () { initScreenSaver(); } //0912 add function ScreenSaver(settings){ ...
- 2018 焦作网络赛 K Transport Ship ( 二进制优化 01 背包 )
题目链接 题意 : 给出若干个物品的数量和单个的重量.问你能不能刚好组成总重 S 分析 : 由于物品过多.想到二进制优化 其实这篇博客就是存个二进制优化的写法 关于二进制优化的详情.百度一下有更多资料 ...
- Java进阶知识03 Hibernate的基础配置详解
1.Hibernate的原理/流程步骤 1.通过Configuration().configure(); 读取并解析hibernate.cfg.xml配置文件,并创建一个configuration对象 ...
- js判断是否是app,及版本号
判断是否是android,ios,qq,wetchat export const Config = {}; Config.ua = navigator.userAgent.toLowerCase(); ...
- template模板循环嵌套循环
template嵌套循环写法:在第一次循环里面需要循环的地方再写个循环,把要循环的数据对象改为第一层的循环对象别名 //template模板循环嵌套循环 <script id="ban ...
- Linux 服务器安装jdk,mysql,tomcat简要教程
linux服务器是阿里云上买的,学生价9.9/月,拿来学习下. 需要准备软件工具: 1.editplus (编辑服务器上的文件) 2.PuTTY (Linux命令连接器) 3.FlashFXP(上传文 ...
- C++入门经典-例7.10-运算符的重载,重载加号运算符
1:曾经介绍过string类型的数据,它是C++标准模版库提供的一个类.string类支持使用加号“+”连接两个string对象.但是使用两个string对象相减确实非法的,其中的原理就是C++所提供 ...
- light4j轻量级微服务应用
最近对light-4j轻框架比较感兴趣,于是对现有应用做了一次重构,现将其间的一些点滴所得分享出来. 项目打包 pom.xml配置了两个profile:debug支持mvn exec:exec启动应用 ...
- go get命令在go mod目录下与正常目录执行的区别
转载自https://www.jianshu.com/p/0a2ebb07da54 非$GOPATH目录下的go mod项目 $ go mod init test $ cat go.mod modul ...
- 过滤器demo-编码统一处理
package com.loaderman.demo.a_loginFilter; import java.io.IOException; import java.lang.reflect.Invoc ...