Django settings: raising KeyError, raising Wrong Configured or use default values?

Django expects you to use environment variables in settings.py to adapt to multiple environments (e.g. local, heroku, AWS).

I assume that I should define, for example, the database username in the environment variable DB_USERNAME . How to read it?

 import os DB_USERNAME = os.environ['DB_USERNAME'] DB_USERNAME = os.environ.get('DB_USERNAME') DB_USERNAME = os.environ.get('DB_USERNAME', 'john') 

Should I grab KeyError and raise ImproperlyConfigured myself? I prefer the application to stop rather than launch it using the wrong settings (by default, people forgetting to set a variable, etc.).

In the case of default values, it may happen that john exists both by mistake and remotely, but with different permissions. It does not look very reliable.

+2
source share
1 answer

I would suggest a different approach to what you are doing.

I am using the following process:

  • Create a .env or .ini file with environment variables in it:

     DB_USERNAME=myDB A_NUMBER=1 ALLOWED_HOSTS=localhost, 127.0.0.1, my_host DEBUG=False MY_DJANGO_KEY=no_peeking_this_is_secret 
  • Use decouple.config to make your life easier - read the .env / .ini file:

    on settings.py :

     from decouple import Csv, config DEBUG = config('DEBUG', cast=bool, default=True) A_NUMBER = config('A_NUMBER') # No cast needed! ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv(), default='') ... 

This will allow you to have multiple .env or .ini files for each of your possible configurations, and you don’t have to worry about mixing permissions, etc.

Finally, I tend to use default values with the minimum allowable allowable values ​​(for example, for allowed hosts by default, which are an empty string).
But if there is a very important variable that must be set correctly, then:

  • The config() method raises the value of UndefinedValueError if the variable is undefined and the default values ​​are not set.

  • Therefore, we can create a try:... except: block to anticipate that:

     try: SUPER_IMPORTANT_VAR = config('SUPER_IMPORTANT_VAR') except UndefinedValueError: print('Hey!! You forgot to set SUPER_IMPORTANT_VAR!!') 
+2
source

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


All Articles