flask/app.py-add_url_rule源码分析
之前分析route方法的时候,可以看到中间会调用add_url_rule方法,add_url_rule方法和route方法一样属于Flask这个类的。
add_url_rule方法主要用来连接url规则。具体工作方法和route类似。如果提供了视图函数,它将会和endpoint名字一起被注册
#装饰器使用方法:
@app.route('/')
def index():
pass # 等同与下面这种方法:
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::
# 如果视图函数没有被提供,需要用下面语法把视图函数和endpoint对应起来
app.view_functions['index'] = index
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 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.
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:
old_func = self.view_functions.get(endpoint)
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
源代码
参数解析:
- rule: 一个字符串格式的url规则,如:"/login". 注:就是从route方法中调用add_url_rule是传递的rule
- endpoint: url规则的名字,用来反向生成url使用,默认是视图函数的名字。注:如果是route方法调用的,则这个参数是route方法传递过来的endpont
- view_func: 视图函数,当对应的endpoint名字被请求时需要调用的函数。注:如果时router方法点用的add_url_rule,则这个参数时router方法传递过来的f
- options: 类似与分析route时候的options.这个options是跟随:class:`~werkzeug.routing.Rule` object定义的,后面会分析这个对象中的具体参数,但有一个methods参数默认是只监听get方法。注:如果是router方法点用的add_url_rule,则这个参数时router方法传递过来的options函数
函数体解析:
def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
if endpoint is None:
# 如果没有提供endpoint参数,则默认用view_func的名字
endpoint = _endpoint_from_view_func(view_func)
# 把endpoint参数添加到options里面
options['endpoint'] = endpoint
# 从options中pop出methods参数,并把值赋给methods变量,如果没有则置为None
methods = options.pop('methods', None)
# moehods的值为None的情况下
if methods is None:
# 如果view_func函数中有这个methods参数,则使用view_func中的。如果没有则赋一个列表('GET',)给methods
methods = getattr(view_func, 'methods', None) or ('GET',)
# 如果methods是字符串类型
if isinstance(methods, string_types):
# 抛出一个异常:methods需要是一个可以迭代的字符串
raise TypeError('Allowed methods have to be iterables of strings, '
'for example: @app.route(..., methods=["POST"])')
# 把methods里面的item都改成大写
methods = set(item.upper() for item in methods) # 在view_func里面定义了一个属性required_methods = ()
# 作用:用来定义一些必须的方法,配合provide_automatic_options使用
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.
# 在view_func里面定义了一个属性provide_automatic_options = None
# 作用:用于禁用和强制启用一些自动选项
provide_automatic_options = getattr(view_func,
'provide_automatic_options', None) # 判断provide_automati_options是否为None
if provide_automatic_options is None:
# 如果OPTIONS字符串没有在methods里面
if 'OPTIONS' not in methods:
# 则把provude_automatic_options改为True,并把OPTIONS添加到required_methods里面
provide_automatic_options = True
required_methods.add('OPTIONS')
# 如果OPTIONS在methods里面,则把provide_automatic_options设置为False
else:
provide_automatic_options = False # 合并required_methods和methods这两个集合到methods里面
methods |= required_methods # 创建路由规则
# 调用url_rule_class方法,由于在Flask类的全局变量中定义了:url_rule_class = Rule, Rule是werkzeug/routing.py里面的一个类
# 也就是相当于实例化了Rule得到了rule对象,具体实例化后的结果请看Rule源码分析
rule = self.url_rule_class(rule, methods=methods, **options)
# 把provide_automatic_options属性添加到rule对象里面
rule.provide_automatic_options = provide_automatic_options # 在Flask类的__init__里面定义了self.url_map = Map(),Map是werkzeug/routing.py里面的一个类
# self.url_map相当与实例化了Map,.add则是调用了Map类里面的add方法
# 具体运行结果,请参考Map源码分析,以及Map源码中的add方法分析
self.url_map.add(rule)
# 如果提供了view_func
if view_func is not None:
# 在flask类的__init__里面定义了self.view_functions = {},
# 从字典里面取endpoint值并赋值为old_func,(endpoint是传递的参数,默认为视图函数名)
old_func = self.view_functions.get(endpoint)
# 如果old_func有值,并且不等于view_func
if old_func is not None and old_func != view_func:
# 则抛出异常:视图函数映射被一个已经存在的函数名重写了
# 也就是说已经存在了一个endpoint:old_func的映射,但是old_fun却不是view_func,也就是说endpoint重复了
raise AssertionError('View function mapping is overwriting an '
'existing endpoint function: %s' % endpoint)
# 添加视图函数与endpoint映射到view_functions字典里面
self.view_functions[endpoint] = view_func
flask/app.py-add_url_rule源码分析的更多相关文章
- FastText总结,fastText 源码分析
文本分类单层网络就够了.非线性的问题用多层的. fasttext有一个有监督的模式,但是模型等同于cbow,只是target变成了label而不是word. fastText有两个可说的地方:1 在w ...
- Python 日志打印之logging.getLogger源码分析
日志打印之logging.getLogger源码分析 By:授客 QQ:1033553122 #实践环境 WIN 10 Python 3.6.5 #函数说明 logging.getLogger(nam ...
- flask框架(三)——路由系统route转换成add_url_rule及源码分析
这节我们不用@app.route来写路由,而是通过add_url_rule 传统写法 (<int:nid>传递int类型参数,endpoint是取别名) @app.route('/det ...
- Flask系列之源码分析(一)
目录: 涉及知识点 Flask框架原理 简单示例 路由系统原理源码分析 请求流程简单源码分析 响应流程简单源码分析 session简单源码分析 涉及知识点 1.装饰器 闭包思想 def wapper( ...
- flask源码分析
本flask源码分析不间断更新 而且我分析的源码全是我个人觉得是很beautiful的 1 flask-login 1.1 flask.ext.login.login_required(func),下 ...
- Flask系列10-- Flask请求上下文源码分析
总览 一.基础准备. 1. local类 对于一个类,实例化得到它的对象后,如果开启多个线程对它的属性进行操作,会发现数据时不安全的 import time from threading import ...
- Flask源码分析二:路由内部实现原理
前言 Flask是目前为止我最喜欢的一个Python Web框架了,为了更好的掌握其内部实现机制,这两天准备学习下Flask的源码,将由浅入深跟大家分享下,其中Flask版本为1.1.1. 上次了解了 ...
- Flask框架(三)—— 请求扩展、中间件、蓝图、session源码分析
Flask框架(三)—— 请求扩展.中间件.蓝图.session源码分析 目录 请求扩展.中间件.蓝图.session源码分析 一.请求扩展 1.before_request 2.after_requ ...
- Flask框架 (四)—— 请求上下文源码分析、g对象、第三方插件(flask_session、flask_script、wtforms)、信号
Flask框架 (四)—— 请求上下文源码分析.g对象.第三方插件(flask_session.flask_script.wtforms).信号 目录 请求上下文源码分析.g对象.第三方插件(flas ...
随机推荐
- [转]java生成 excel 并导出文件
原文:https://blog.csdn.net/xunwei0303/article/details/53213130 目前,比较常用的实现Java导入.导出Excel的技术有两种Jakarta P ...
- lintcode 394. Coins in a Line 、leetcode 292. Nim Game 、lintcode 395. Coins in a Line II
变型:如果是最后拿走所有石子那个人输,则f[0] = true 394. Coins in a Line dp[n]表示n个石子,先手的人,是必胜还是必输.拿1个石子,2个石子之后都是必胜,则当前必败 ...
- shell编程系列9--文本处理三剑客之sed概述及常见用法总结
shell编程系列9--文本处理三剑客之sed概述及常见用法总结 sed的工作模式:对文本的行数据一行行处理,如下图 sed(stream editor),是流编辑器,依据特定的匹配模式,对文本逐行匹 ...
- Dart中的数据类型转换:
int -> string age.toString() string -> int int.parse('100'); String -> double 1 var onePoin ...
- Python3入门(十三)——常用内置模块之时间日期模块datatime
1.日期时间模块——datatime //其他模块例如time.calender等模块暂不展开 (1)获取当前时间:datatime.now(): from datetime import datet ...
- Qt编写气体安全管理系统2-界面框架
一.前言 整体框架包括两个部分,一部分是UI界面框架,比如一级二级导航菜单按钮整体布局等,一部分是项目框架,上一篇文章说的是项目框架,这一篇文章来说界面框架,Qt做界面非常快速和高效,尤其是提供了可视 ...
- Android开发之高仿微信图片选择器
记得刚开始做Andriod项目那会,经常会碰到一些上传图片的功能需求,特别是社交类的app,比如用户头像,说说配图,商品配图等功能都需要让我们到系统相册去选取图片,但官方却没有提供可以选取多张图片的相 ...
- DEBUG技巧1 SE37将参数保存为测试数据
1. SE37调试函数的时候,将参数保存为测试数据,供下次调试使用, 或者参考标准的赋值进行赋值 2. SE37 ->执行-> 测试序列 测试函数: CO_XT_COMPONENTS_DE ...
- 【分布式一致性】etcd
etcd: https://jimmysong.io/kubernetes-handbook/concepts/etcd.html 什么是 分布式一致性: http://thesecretliveso ...
- hdu 2018 母牛的故事 动态规划入门题
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2018 设 f[i][j] 表示第i天年龄为j的母牛个数,其中j=4代表所有年龄达到4岁的成年母牛,则: ...