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

您必须在包装器中实际调用该函数。

return view_func(request, *args, **kwargs)
于 2013-08-23T07:33:06.510 回答
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 回答