how to create decorator function in django 1

how to create decorator function in django

# aDecorator is the wrapper function 
def aDecorator(func):     #func is the wrapped function
   def wrapper(*args, **kwargs):
      ret = func(*args, **kwargs)  #get reault of wrapped function
      return f' Decorator has converted result to upper-case: {ret.upper()} '
   return wrapper          #wrapper contains the decoration and result of wrapped function 

@aDecorator                # aDecorator is the wrapper function
def exampleFunction():
   return "basic output"   #lower-case string

print(exampleFunction())   #addDecoration adds note and converts to Upper-case

#Output:
#  Decorator has converted result to upper-case: BASIC OUTPUT 

Here is what the above code is Doing:
1. The @aDecorator line is a shortcut for exampleFunction = aDecorator(exampleFunction)
2. The aDecorator function is called with the exampleFunction as an argument.
3. The aDecorator function returns the wrapper function.
4. The wrapper function is called with the arguments and keyword arguments that were passed to the decorated function.
5. The wrapper function returns the result of calling the decorated function.

Similar Posts