Django: is it better to import variables from settings.py file or main configuration file?

I was wondering if it is better to import the variables into your view from the settings.py file? or is it better to create a configuration file with the necessary variables?

I like to write configuration files for my Django applications, read and import variables from there when necessary. For instance:

.configrc

[awesomeVariables] someMagicNumber = 7 

views.py

 from ConfigParser import SafeConfigParser #Open and parse the file config = SafeConfigParser() config.read(pathToConfig) #Get variable magicNumber = config.get('awesomeVariables', 'someMagicNumber')) 

However, I noticed that some programmers prefer the following:

settings.py

 SOME_MAGIC_NUMBER=7 

views.py

 import settings magicNumber = settings.SOME_MAGIC_NUMBER 

I was curious about the pros and cons of different methods? Is it possible to import variables directly from your settings, violate the integrity of the architecture?

+4
source share
3 answers

This is a call to judgment. Using the settings module is the “Django path”, although you should do from django.conf import settings; settings.MY_SETTING from django.conf import settings; settings.MY_SETTING , which DJANGO_SETTINGS_MODULE will respect. But Django is just Python; there is nothing to prevent you from using ConfigParser . It is in the interest of having only one place where such things are defined, I would recommend placing it in the Django settings file, but if you have a reason not to do this, do not.

+5
source

Using the configuration file is completely un-Django. Settings are in settings.py. Period. For application-specific parameters, you simply set the default in your application and allow the user to override .py in your project settings:

 from django.conf import settings SOME_MAGIC_NUMBER = settings.SOME_MAGIC_NUMBER if hasattr(settings, 'SOME_MAGIC_NUMBER') else 0 # Where `0` is the default value 
+1
source

There is also an application for dynamically saving settings in db. Maybe you find it useful. django-constance

+1
source

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


All Articles