2012-08-05 33 views
0

創建裝飾我的看法:如何在Django用於裝飾圖

@decorator 
def func(request): 
    hello = "hello" 
    return render_to_responce("test.html", locals()) 

和模板的test.html:

{{ hello }} 
{{ username }} 

我想寫裝飾爲func(request),還增加了一個變量名,用戶名,到函數並返回模板中的兩個參數。我試圖使它如下:

def decorator(func): 
    def wrapper(request, *args, **kwargs): 
     username = request.user.username 
     q = func(request, *args, **kwargs) 
     #what I need add here I do not know ... 
     return q 
    return wrapper 
+0

你爲什麼想要裝飾者?你能解釋一下用例嗎? (你是否也可以清理你的代碼,使它在語法上正確並且更具可讀性)? – 2012-08-05 16:00:29

回答

5

如果你的觀點是這樣的:

def func(request, username): 
    hello = "hello" 
    return render_to_responce("test.html", locals()) 

你可以寫一個這樣的裝飾:

from functools import wraps 
def pass_username(view): 
    @wraps(view) 
    def wrapper(request, *args, **kwargs): 
     return view(request, request.user.username, *args, **kwargs) 
    return wrapper 

,然後用它像:

@pass_username 
def func(request, username): 
    hello = "hello" 
    return render_to_response("test.html", locals()) 

(只要確保你將把它在urls.py,如果它是def func(request):,沒有username - 這種說法將被裝飾提供)

但事實上這是一個並不真正需要單獨的裝飾(反正,它只是一個額外的非常簡單的例子在視圖定義中)。

+0

同意這是一個簡單的情況,不應該需要一個裝飾器,但反正會使用'functools.wraps' – 2012-08-05 16:06:15

+0

@JonClements:同意,這確實是更好的方法。我已經更新了我的答案。 – Tadeck 2012-08-05 16:08:57

相關問題