Ale*_*oca 5 python decorator flask python-decorators
在Flask中,我为每个路由使用了一组装饰器,但代码是"丑陋的":
@app.route("/first")
@auth.login_required
@crossdomain(origin='*')
@nocache
def first_page:
....
@app.route("/second")
@auth.login_required
@crossdomain(origin='*')
@nocache
def second_page:
....
Run Code Online (Sandbox Code Playgroud)
我希望有一个声明,将所有这些声明与一个装饰器组合在一起:
@nice_decorator("/first")
def first_page:
....
@nice_decorator("/second")
def second_page:
....
Run Code Online (Sandbox Code Playgroud)
我尝试按照答案在Can中将两个装饰器合并为一个装饰器吗?但我不能让它工作:
def composed(*decs):
def deco(f):
for dec in reversed(decs):
f = dec(f)
return f
return deco
def nice_decorator(route):
composed(app.route(route),
auth.login_required,
crossdomain(origin="*"),
nocache)
@nice_decorator("/first")
def first_page:
....
Run Code Online (Sandbox Code Playgroud)
因为这个错误,我不明白:
@nice_decorator("/first")
TypeError: 'NoneType' object is not callable
Run Code Online (Sandbox Code Playgroud)
根据其中一条评论,我使用另一种形式定义了它,但无法指定路由参数:
new_decorator2 = composed(app.route("/first"),
auth.login_required,
crossdomain(origin="*"),
nocache)
Run Code Online (Sandbox Code Playgroud)
是否可以使用参数定义单个装饰器?
你没有正确定义构图.您需要将定义更改为nice_decorator以下内容:
def nice_decorator(route):
return composed(
app.route(route),
auth.login_required,
crossdomain(origin="*"),
nocache
)
Run Code Online (Sandbox Code Playgroud)
您之前的版本从未实际返回任何内容 Python不像Ruby或Lisp,其中最后一个表达式是返回值.
| 归档时间: |
|
| 查看次数: |
366 次 |
| 最近记录: |