1

I want to load a number of classes I've put in a module that's not part of the settings.INSTALLED_APPS list. (I want my customers to be able to write their own subclasses which can be dynamically loaded or reloaded.) I have a function called load_classes() to do so. The question is where to call it when my project initially starts.

My first attempt at this was placing load_classes in the ready() function of AppConfig as per this question, but that apparently only is invoked after the particular app with the AppConfig is done loading, not all of them. Since these class definitions import models and functions from other apps in the project, I ended up with this error:

File "/Users/dylan/.local/share/virtualenvs/pipeproj-oDyHbVBN/lib/python3.8/site-packages/django/apps/registry.py", line 135, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

Where can I place my importing code, so it's triggered once all of the Django apps have been loaded?

Dylan
  • 2,315
  • 2
  • 20
  • 33

2 Answers2

2

after some time trying to figure out how to do this, I came up with the following:

def wait_for_ready_event(ready_event):
    print('wait_for_event starting')
    event_is_set = ready_event.wait()

    try:
        # code
    except Exception as e:
        _thread.interrupt_main()

    print('event set: %s', event_is_set)

t1 = threading.Thread(name='model_validator',
                      target=wait_for_ready_event,
                      args=(apps.ready_event,))
t1.start()

if you lode this code in at any point in the app, it will wait for the main thread to send out the ready_event signal, and then your new thread can run its code

Zev Baker
  • 21
  • 3
1

Willem Van Onsem's comment prodded me to look at my entire apps.py file where I call the ready function. Though I was using importlib.import_module for the dynamic loading, I had another totally separate import at the top of the file that drew upon other apps. Once I took that out I got past the error.

So the lesson is, contain all dependencies on other apps to within the AppConfig.ready call. Thanks, Willem!

Dylan
  • 2,315
  • 2
  • 20
  • 33