先来普及下python装饰器,有装饰器带变量的,有装饰器不带变量
def decor(func):
print("这是最外层func函数")
def wrapper(*args,**kwargs):
print("内层装饰器函数")
func(*args,**kwargs)
return wrapper
@decor
def hello():
print("小明要上课了")
这个运行结果
这是最外层func函数
def decor(func):
print("这是最外层func函数")
def wrapper(*args,**kwargs):
print("内层装饰器函数")
func(*args,**kwargs)
return wrapper
@decor
def hello():
print("小明要上课了")
hello()
执行结果
这是最外层func函数
内层装饰器函数
小明要上课了
带有变量的装饰器
def first(a,b):
print(f"变量a的值是{a}变量b的值是{b}")
def wraper(func):
def innerfun(*args,**kwargs):
func(*args,**kwargs)
print("这是最内层函数")
return innerfun
return wraper
@first(1,2)
def hello():
print("小明要上课了")
运行结果
变量a的值是1变量b的值是2
def first(a,b):
print(f"变量a的值是{a}变量b的值是{b}")
def wraper(func):
def innerfun(*args,**kwargs):
func(*args,**kwargs)
print("这是最内层函数")
return innerfun
return wraper
@first(1,2)
def hello():
print("小明要上课了")
hello()
执行结果
变量a的值是1变量b的值是2
小明要上课了
这是最内层函数
第二种带有参数装饰器写法
def first(a,b):
print(f"变量a的值是{a}变量b的值是{b}")
def wraper(func):
print("这个也是要执行的")
return func
return wraper
@first(1,2)
def hello():
print("小明要上课了")
执行结果
变量a的值是1变量b的值是2
这个也是要执行的
注意上面的warper函数执行了,函数使用了装饰器但是函数还没调用
执行函数:
def first(a,b):
print(f"变量a的值是{a}变量b的值是{b}")
def wraper(func):
print("这个也是要执行的")
return func
return wraper
@first(1,2)
def hello():
print("小明要上课了")
hello()
执行结果
变量a的值是1变量b的值是2
这个也是要执行的
小明要上课了
上面这些是一些基础知识,为今天的主题app.route装饰器做铺垫
在蓝图里面使用装饰器都是下面这样的
@ac.route('/test',methods=['GET'])
def test():
print(g)
g.name=200
print(g.name)
return "hello world%s"%g.name
app.route源码如下
def route(self, rule, **options):
"""Like :meth:`Flask.route` but for a blueprint. The endpoint for the
:func:`url_for` function is prefixed with the name of the blueprint.
"""
def decorator(f):
endpoint = options.pop("endpoint", f.__name__)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
根据上面装饰器基本知识可以知道在程序编译过程中已经调用了add_url_rule这个函数,所以和django的urlpatterns一样,在程序启动的时候已经对所有的url请求地址初始化了,add_url_rule这个就不深入研究了,是一个很复杂过程,喜欢了解的去读源码了解,然后给我科普
为了验证上面的url和函数一一对应在监听启动的时候已经生成,在程序的主入口处直接打印出来
在manager.py程序调用入口处直接打印出来
app=create_app()
db.init_app(app)
print("app的所有url注册的连接",app.url_map)
migrate = Migrate(app,db)
manager=Manager(app)
manager.add_command('db',MigrateCommand)
打印了url
上面的url已经打印
- 技术无止境