This article mainly introduces the tips for merging multiple decorators in Python. This article uses the method of rewriting and calling the function to merge multiple decorators into one row and one function for calling, you can refer to the django program and need to write a lot of Apis. each function requires several decorators, for example
The code is as follows:
@ Csrf_exempt
@ Require_POST
Def foo (request ):
Pass
Since two or more decorators are required for multiple methods, how can we merge them into one row?
The above function execution process should be
The code is as follows:
Csrf_exempt (require_POST (foo ))
Modify
The code is as follows:
Def compose (* funs ):
Def deco (f ):
For fun in reversed (funs ):
F = fun (f)
Return f
Return deco
Function
The code is as follows:
@ Compose (csrf_exempt, require_POST)
Def foo (request ):
Pass
Refer:
Can I combine two decorators into a single one in Python