This article mainly introduces Python Tips for merging multiple decorators. This article uses the method of rewriting and calling function to merge multiple decorators into one line and one function. Call, friends who need it can refer to the
django program. You need to write a lot of APIs. Each function requires several decorators, such as
@csrf_exempt @require_POST def foo(request): pass
Since there are so many Each method needs to write two decorators, or more. Is there any way to combine multiple decorators into one line?
The execution process of the above function should be
The code is as follows:
csrf_exempt(require_POST(foo))
is modified to
def compose(*funs): def deco(f): for fun in reversed(funs): f = fun(f) return f return deco
The function is rewritten to
@compose(csrf_exempt, require_POST) def foo(request): pass
The above is the detailed content of Is it suitable to combine multiple decorators using Python?. For more information, please follow other related articles on the PHP Chinese website!