Last active
March 11, 2017 06:37
-
-
Save devraj/c1856834c8bd454eb4c6c39cd44a737c to your computer and use it in GitHub Desktop.
Decorator experiments to see what order they get executed in and how we can pass parameters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
""" | |
The object here is to demonstrate the following about Python decorators: | |
- All decorators that execute logic prior to calling the decorated function | |
executed before the decorators that execute logic after the decorated | |
function executes | |
- Order or application of the decorators does not break the point above | |
- Ensuring order of operations of pre-hook decorators | |
- Passing parameters to decorators | |
""" | |
from functools import wraps | |
def request(method): | |
def request_wrapper(handler): | |
wraps(handler) | |
def request_parser(*args, **kwargs): | |
print("PRE >> Do my request parsing first %s" % method) | |
return handler(*args, **kwargs) | |
return request_parser | |
return request_wrapper | |
def authentication(handler): | |
wraps(handler) | |
def response_wrapper(): | |
print("PRE >> Running authentication checks") | |
return handler() | |
return response_wrapper | |
def response(handler): | |
wraps(handler) | |
def response_wrapper(): | |
handler_response = handler() | |
#: This would process the response from the handler | |
print("POST >> Processing response %s" % handler_response) | |
return handler_response | |
return response_wrapper | |
@response | |
@request(method="GET") | |
def handler_endpoint(): | |
print("MAIN >> Handler with response, request") | |
return "GET Response" | |
@response | |
@authentication | |
@request(method="POST") | |
def handler_decorator_order_1(): | |
print("MAIN >> Handler with response, auth, request") | |
return "POST Response" | |
@request(method="PUT") | |
@authentication | |
@response | |
@response | |
def handler_decorator_order_2(): | |
print("MAIN >> Handler with request, auth, response") | |
return "PUT Response" | |
if __name__ == '__main__': | |
print("Handler Test:") | |
handler_endpoint() | |
print("\nHandler with incorrect order:") | |
handler_decorator_order_1() | |
print("\nHandler with incorrect order:") | |
handler_decorator_order_2() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment