Home >Backend Development >Python Tutorial >Is it suitable to combine multiple decorators using Python?

Is it suitable to combine multiple decorators using Python?

伊谢尔伦
伊谢尔伦Original
2017-06-28 13:24:382084browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn