我正在爲WSGI + Werkzeug應用程序中的視圖編寫「login_required」裝飾器。Python - 在裝飾器中獲取原始函數參數
爲了做到這一點,我需要獲取用戶的會話,該會話可通過傳遞給視圖方法的Request對象訪問。
雖然,我無法弄清楚如何獲得裝飾器中的Request實例。我看了PEP318,特別是第四個例子,但我還沒有完全理解它。
這裏就是我想:
def login_required(*args, **kw):
def goto_login(**kw):
return redirect(url_for('login'))
def decorate(f):
# args[0] should be request
args[0].client_session['test'] = True
logged_in = 0
if logged_in:
return f
else:
return goto_login
return decorate
@login_required()
@expose('/hello/<string:name>')
def hello(request, name):
return render_template('say_hello.html', name=name)
,但我得到一個索引越界錯誤試圖調用args[0]
的。
有沒有什麼辦法可以訪問傳遞到「login_required」裝飾器中的「hello」函數的請求參數?
完美!我使用的是「公開」裝飾器中使用的不同語法 - 我不確定我是否理解備用語法。 – ashgromnies 2009-06-18 00:11:00