栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python > python框架

flask route装饰器如何理解

python框架 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

flask route装饰器如何理解

flask装饰器route实现路由功能理解

利用装饰器的方式实现了路由函数,这是一个十分简单清晰的结构,而这个功能的实现,有着很大的学习意义

@appweb.route('index',methods=['GET','POST']
def static1():
    return render_template('index.html')

看代码可以知道,通过appweb.route装饰了static1()函数,使其成为了路由函数

解析route装饰器源代码

def route(self,rule,**options):

    def decorator(f):
        endpoint = options.pop('endpoints',None)
        self.add_url_rule(rule,endpoint,f,**options)
        return f
    return decorator

Flask实例的主要路由功能就是这个route函数,而route函数源代码可以看出,是一个3层嵌套的装饰器(route函数内部还有个装饰器)

三层嵌套装饰器的语法糖规则

@appweb.route('index',methods=['GET','POST'])
def static1():
    return render_template('index.html')
#等于
static1 = appweb.route('index',methods=['GET','POST'])(static1)

总结

上面的route函数,实际上是返回一个decorator,这个decorator函数装饰static1函数成为路由函数

route函数的功能是提供rule参数和其他的字典键对值参数(**options)

self.add_url_rule是关键的函数,它将f参数(即static1())装饰成路由函数,最后return f

关于add_url_rule函数,从更深的源码可知,默认方法为GET,将rule(即'/index')作为网址注册进了路由,大部分的参数都在options字典中,目前我已知的参数有methods=,endpoints=,view_func=等。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/12983.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号