Django - How To Use .Env File For Storing Sensitive Setting Values
Django - How To Use .Env File For Storing Sensitive Setting Values
OK, again while learning I came across a through that how I can use the .env file to
store my local/stage/production related setting values which are either local to my
system or sensitive enough, like database password/email configuration/etc.., not to
share or commit in to the source control.
https://medium.com/@jatin_95284/django-how-to-use-env-file-for-storing-sensitive-setting-values-6c9f8817e9d7 1/3
22/01/2020 Django: How to use .env file for storing sensitive setting values
I wrote a small and simple block of code to read the .env file and set the settings value
when the application first loads.
1 import os
2
3 env_settings = None
4
5
6 def env(key, default=None):
7 global env_settings
8 env_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
9 if os.path.exists(env_file_path) and env_settings is None:
10 print('env_settings not set (first)')
11 env_reader = open(env_file_path, mode='rt', encoding='utf-8')
12 env_settings = env_reader.readlines()
13 env_reader.close()
14 for setting in env_settings:
15 setting_key, value = setting.split('=')
16 value = value.strip()
17 if setting_key.strip() == key:
18 if value == 'False':
19 return False
20 if value == 'True':
21 return True
22 return value.strip()
23 return default
In the above code you can see that I’m loading the .env file from the directory where we
have settings.py file resides. In this file I read the .env file lines and then check for the
provided key. If the key finds, I return the value otherwise the default will return which
is None by default.
As of now, the code only supports to read string/int values. The code does not support the
JSON/LIST type of settings from .env file. Also, provide the list type of settings in a single
line just like shown below in a sample .env.
EMAIL_HOST = smtp.jatin.prajapati
EMAIL_HOST_USER = jatinpr
EMAIL_HOST_PASSWORD = mysamplepassword
EMAIL_PORT = 578
https://medium.com/@jatin_95284/django-how-to-use-env-file-for-storing-sensitive-setting-values-6c9f8817e9d7 2/3
22/01/2020 Django: How to use .env file for storing sensitive setting values
Now you can use the ‘env’ function like following in your settings.py file:
EMAIL_HOST = env('EMAIL_HOST')
EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD')
EMAIL_HOST_USER = env('EMAIL_HOST_USER')
EMAIL_PORT = env('EMAIL_PORT')
STATICFILES_DIRS = env('STATICFILES_DIRS')
So, using this small code block we can save the local settings or sensitive information
out of the source control and avoid accidental sharing of such information.
https://medium.com/@jatin_95284/django-how-to-use-env-file-for-storing-sensitive-setting-values-6c9f8817e9d7 3/3