Search code examples
pythondjangopython-3.xpython-decorators

How to execute a decorator function at startup in a Django/Python Application?


I have a number of classes for which I wish to run a decorator function on. As I am aware decorators only run when the class/function/whatever they label is loaded into the code.

e.g.

def decorator(cls):
  print("Decorator executed")
  return cls

@decorator
class Example:
  pass

Example()

How can I trigger the decorator function on all the classes a decorator labels at startup of the django application without having to load each class separately? (or without having knowledge of the classes for which a decorator labels)


Solution

  • Solution Update:

    I had a bunch of classes for which I wanted to run a decorator function on and they all contained 'Model' in their classname. Decorators on classes are executed upon an import of the given class so as a work around I made a function (which ran at startup) to import all classes containing 'Model' in their classname and as a byproduct the decorator function ran against all of these classes.

    import glob
    import importlib.util
    
    
    def execute_decorator_against_classes():
        for filename in glob.iglob("**/*Model.py",
                                   recursive=True):
            module_name = filename.split("/")
            module_name = module_name[len(module_name) - 1]
            module_name = module_name[:module_name.rfind('.py')]
            spec = importlib.util.spec_from_file_location(module_name,
                                                          filename)
            foo = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(foo)