2017-10-04 114 views
4

在瓶我使用了一组装饰各条路线的,但代码是“丑”组装饰:如何在Python

@app.route("/first") 
@auth.login_required 
@crossdomain(origin='*') 
@nocache 
def first_page: 
    .... 

@app.route("/second") 
@auth.login_required 
@crossdomain(origin='*') 
@nocache 
def second_page: 
    .... 

我宁愿有一个声明组所有的人与单一的装饰:

@nice_decorator("/first") 
def first_page: 
    .... 

@nice_decorator("/second") 
def second_page: 
    .... 

我试图按照答案在Can I combine two decorators into a single one in Python?,但我不能让它工作:

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: 
    .... 

因为这个错误,我不明白:

@nice_decorator("/first") 
TypeError: 'NoneType' object is not callable 

下面我用另一种形式的工作,但没有可能到指定路由参数定义它的评论之一:

new_decorator2 = composed(app.route("/first"), 
          auth.login_required, 
          crossdomain(origin="*"), 
          nocache) 

是否有可能用参数定义一个装饰器?

+2

'nice_decorator'不会返回任何内容,因此返回'None'和'None'不可调用。在'合成(app.route ...)之前添加'return'^ – Arount

回答

5

您没有正确定义构图。你需要的nice_decorator的定义修改为这样的事情:

def nice_decorator(route): 
    return composed(
     app.route(route), 
     auth.login_required, 
     crossdomain(origin="*"), 
     nocache 
    ) 

你以前的版本实际上从未返回任何东西。 Python不像Ruby或Lisp,其中最后一个表达式是返回值。

+1

让你们大家一起! 我完全忘记了回报。 –