Is it possible to dynamically load django applications at runtime? Typically, applications are loaded during initialization using the INSTALLED_APPS tuple in settings.py. However, is it possible to download additional applications at run time? I face this problem in different situations. For example, one situation occurs during testing, when I want to dynamically load or unload applications.
To make the problem more specific, imagine that I have a directory called apps where I put my applications, and I would like to automatically install any new application that appears there, without manually editing settings.py.
It is quite simple. Following the code example in
Django: dynamically add applications as a plugin, automatically create URLs and other parameters
we placed the following code in settings.py so that we could iterate over the names of all subdirectories in the application directory and increase the INSTALLED_APPS tuple in settings.py as follows:
APPS_DIR = '/path_to/apps/' for item in os.listdir(APPS_DIR): if os.path.isdir(os.path.join(APPS_DIR, item)): app_name = 'apps.%s' % item if app_name not in INSTALLED_APPS: INSTALLED_APPS += (app_name, )
After that, if I were in a Django shell, I could be something like
from django.conf import settings
and applications will be listed in settings.INSTALLED_APPS . And if I did
from django.core import management management.call_command('syncdb', interactive=False)
this will create the necessary database tables for the applications.
However, if I now added several applications to the apps/ directory without restarting, they would not be listed in settings.INSTALLED_APPS, and therefore a subsequent call to syncdb would have no effect.
I would like to know if there is something that I could do - without restarting - to reload the settings and download / install new applications.
I tried to import my settings.py directly, i.e. from myproject import settings
and then reload these settings using inline Python after any change to the app directory. Although settings.INSTALLED_APPS is now changing to include new applications, this ultimately does not matter. For example,
from django.db import models models.get_apps()
shows only original applications in apps and not recently added and similarly
management.call_command('syncdb', interactive=False)
will not see recently added applications.
As I said above, I reflected on this situation, especially in the context of testing, where I dynamically added or removed applications.
Ps. I work with django 1.6, but on the advice of @RickyA, I see that django has some significant changes in application processing in 1.7
https://docs.djangoproject.com/en/1.7/ref/applications/
I'm still not sure what this might mean for the problem I am facing.