2

私は見解を持っています:

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

およびテンプレートtest.html:

{{ hello }}
{{ username }}

func(request)関数に変数USERNAMEを追加し、テンプレートに2つのパラメーターを返す、のデコレーターを作成したいと思います。私はそれを次のようにしようとしました:

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
4

1 に答える 1

7

ビューが次のようになっている場合:

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-この引数はデコレータによって提供されます)

しかし実際、これは非常に単純なケースであり、個別のデコレータは実際には必要ありません(とにかく、ビュー定義の1行だけ追加されます)。

于 2012-08-05T16:02:29.657 に答える