2017-10-04 115 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

讓你們大家一起! 我完全忘記了回報。 –