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)
是否有可能用參數定義一個裝飾器?
'nice_decorator'不會返回任何內容,因此返回'None'和'None'不可調用。在'合成(app.route ...)之前添加'return'^ – Arount