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

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


  • 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:
    def decorator_function(function_to_decorate):
    	def wrapper_for_passed_function():
    		print("Before function.")
    		print("After function.")
    	return wrapper_for_passed_function
    def outer_decorater_function(function_to_decorate):
    	def wrapper_for_passed_function():
    		print("Before outer function.")
    		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.")
    def function_to_be_multiply_decorated():
    	print("Funciton to be multiply decorated.")
    # Function without wrapper
    print("*** Without wrapper ***")
    # Funtion with wrapper
    print("\n*** With wrapper ***")
    wrapped_function = decorator_function(function_to_be_wrapped)
    # Using a decorators
    print("\n*** Using a decorator ***")
    # Using multiple decorators
    print("\n*** Using multiple decorators ***")