The right way to import one Django settings constant to avoid the extra cost of importing settings?

From Django - The difference between the django.conf.settings import and import options , I understand that the accepted way to import the settings file is:

from django.conf import settings 

I also read Good or bad practice in Python: import in the middle of a file . One answer there will lead you to http://mail.python.org/pipermail/python-list/2001-July/699176.html , where points number 2 and number 4 relate to my question.

Say I have a huge settings.py parameter and throughout my Django code, I only need to use a β€œmodest” constant, such as MEDIA_ROOT, in one rarely called method. Thus, it is incredibly wasteful to import all settings.py:

 from django.conf import settings ... def foo(): my_media_root = settings.MEDIA_ROOT 

when I can just import the necessary constant:

 from settings import MEDIA_ROOT ... def foo(): my_media_root = MEDIA_ROOT 

and therefore, avoid importing huge settings.py parameters, especially since it can never be used if my_media_root is used in only one of many methods in this file. Of course, this is bad practice, but the "good practice version" of this does not work:

 from django.conf.settings import MEDIA_ROOT ... def foo(): my_media_root = MEDIA_ROOT 

since by design it throws the expected exception ImportError: No module named settings .

So my question is: what is the way to import only one constant from a large settings.py? Thanks in advance.

+4
source share
1 answer

If this is a Django project, the settings file has already been imported, you have nothing to just import it and use the constant you want. Importing a module multiple times in Python is done only once.

The usual way to import settings is:

 from django.conf import settings 

It simply assigns a single name in your module ( settings ) the value of an existing already imported settings object. This is equivalent and has roughly the same runtime as:

 settings = sys.modules['django.conf'].settings 

Having trouble with this easy way?

+11
source

Source: https://habr.com/ru/post/1396742/


All Articles