2


条件が満たされた場合に another_decorator を適用し、それ以外の場合は単に関数 を適用するデコレータを定義したいと思います。

以下は動作しません..

def decorator_for_post(view_func):

    @functools.wraps(view_func)
    def wrapper(request, *args, **kwargs):

        if request.method == 'POST':
            return another_decorator(view_func) # we apply **another_decorator**
        return view_func  # we just use the view_func

    return wrapper
4

2 に答える 2

2

次のような意味ですか。

class Request:
    def __init__ (self, method):
        self.method = method

def another_decorator (f):
    print ("another")
    return f

def decorator_for_post (f):
    def g (request, *args, **kwargs):
        if request.method == "POST":
            return another_decorator (f) (request, *args, **kwargs)
        return f (request, *args, **kwargs)
    return g

@decorator_for_post
def x (request):
    print ("doing x")

print ("GET")
x (Request ("GET") )
print ("POST")
x (Request ("POST") )
于 2013-08-23T07:37:51.613 に答える
2

ラッパー内で実際に関数を呼び出す必要があります。

return view_func(request, *args, **kwargs)
于 2013-08-23T07:33:06.510 に答える