Decorators

To request database connections, flaskr uses decorators. For example:

@app.before_request
def before_request():
    g.db = connect_db()

From http://stackoverflow.com/questions/739654/understanding-python-decorators:

  • Functions are objects in python and can be assigned to a variable.
  • Functions can be embedded inside other functions, but the inner function is in-scope only within the outer function.
  • A function can be passed as a parameter to another function.
  • A decorator is a function that expects ANOTHER function as parameter.
  • Decorators allow extra code to be run before and after the code that they decorate.
  • Multiple decorators can be added to a function.
  •  

    Based on this explanation, here is an example of decorator usage:
    # Code showing decorators
    # Based on explanation of decorators in:
    # http://stackoverflow.com/questions/739654/understanding-python-decorators
    
    def decorator_function(function_to_decorate):
    	def wrapper_for_passed_function():
    		print("Before function.")
    		function_to_decorate()
    		print("After function.")
    
    	return wrapper_for_passed_function
    
    def outer_decorater_function(function_to_decorate):
    	def wrapper_for_passed_function():
    		print("Before outer function.")
    		function_to_decorate()
    		print("After outer function.")
    
    	return wrapper_for_passed_function
    
    def function_to_be_wrapped():
    	print("Function to be wrapped.")
    
    @decorator_function # Shortcut to wrapped_function = decorator_function(function_to_be_decorated
    def function_to_be_decorated():
    	print("Function to be decorated.")
    
    @outer_decorater_function
    @decorator_function
    def function_to_be_multiply_decorated():
    	print("Funciton to be multiply decorated.")
    
    # Function without wrapper
    print("*** Without wrapper ***")
    function_to_be_wrapped()
    
    # Funtion with wrapper
    print("\n*** With wrapper ***")
    wrapped_function = decorator_function(function_to_be_wrapped)
    wrapped_function()
    
    # Using a decorators
    print("\n*** Using a decorator ***")
    function_to_be_decorated()
    
    # Using multiple decorators
    print("\n*** Using multiple decorators ***")
    function_to_be_multiply_decorated()