Tips for merging multiple decorators in Python-Python tutorial

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.