@app.route源码流程分析
2024-08-31 14:27:39
@app.route(), 是调用了flask.app.py文件里面的Flask类的route方法,route方法所做的事情和add_url_rule类似,是用来为一个URL注册一个视图函数,但是我们知道route方法是以装饰器的方式使用的
def route(self, rule, **options):
"""sage::
@app.route('/')
def index():
return 'Hello World'
: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):
endpoint = options.pop('endpoint', None)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
源代码
参数解析
- rule: 一个字符串格式的url规则,如:"/login"
- endpont: 被注册的url的名字,一般用来反向生成url的时候使用,默认把视图函数的名字作为endpoint,如:endpoint="login"
- **options: 这个options是跟随:class:`~werkzeug.routing.Rule` object定义的,后面会分析这个对象中的具体参数,但有一个methods参数默认是只监听get方法。
函数体解析
# 根据route的装饰器使用方法,我们可以知道f参数就是视图函数。
def decorator(f):
# 如果options参数中有endpoint则弹出endpoint,并把值赋值给endpoint变量,如果没有则赋值为None
endpoint = options.pop('endpoint', None)
# 调用add_url_rule方法,并把rule,endpont,f,**options传递进来,并执行这个方法,详见add_url_rule方法源码分析
self.add_url_rule(rule, endpoint, f, **options)
# 返回了返回f
return f
最新文章
- .NET面试题系列[2] - .NET框架基础知识(2)
- C# async and await
- 重置mysql数据库密码
- paip.提升效率--gui 的选择--swing最佳实践swt awt
- 红包算法思考和总结 -- by jason.zhi
- 使用spring+hibernate+atomikos+tomcat构建分布式事务
- 使用Navicat for Oracle 出现的错误
- 在多线程环境中使用Jedis
- 自己写的sql排序
- bzoj3932
- 微信小程序之购物车功能
- Java之GC
- window下安装cross-env解决NODE_ENV ts-node 不是内部或外部命令,也不是可运行的程序 或批处理文件 问题
- FastReport 打印模版页(TFrxReportpage)复制
- 基础I/O接口与操作
- OpenCV 图形变换
- Selenium2+python自动化49-判断文本(text_to_be_present_in_element)
- 【Demo】jQuery 图片放大镜效果——模仿淘宝图片放大效果
- SQL SERVER SA密码忘记,windows集成身份验证都登录不了不怎么办
- PHP -- 简单表单提交