How to secure sensitive data in a Django Python

Listen as audio
secure sensitive data in a django
Image by Darwin Laganzon from Pixabay

Hello Techies,

It’s not good practice to secure sensitive data in a Django settings.py file. As you know this world is full of hackers so the possibilities of stealing your sensitive data are high. So in this blog, I’m telling you How to secure sensitive data in a Django related project.

When most developers start their Django-based project, they store all the sensitive information, such as secret key, database information, in the settings.py file. Now the problem is that if you are working in a team and you are pushing the code into the git and if someone is allowed to see that code then he can see all your confidential information. 

If you are developing any web-based project, the project must be secure and should be a priority for any developer. 

settings.py file has the most sensitive data. We can secure sensitive data in a Django using python-decouple Library. It is a very powerful library for separating parameters from the source code. We will create a file (Eg: .env or .ini) and keep some parameters in it, like a secret key, database configuration, password, debug status, allowed hosts, etc

Secure sensitive data in a Django

Installation

pip install python-decouple

How to use python decouple library to secure sensitive data in a Django Application

Let’s consider your  settings.py file as it looks like below.

import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'nizatuzy04kzvoyj1wy7)(g$&99m)-e28$h9-mjz7_$6fbp0a*'
ALLOWED_HOSTS = ['localhost', '127.0.0.1'] 
DEBUG = True
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'demo', # example - database information
        'USER': 'demo',
        'PASSWORD': 'demo',
        'HOST': '127.0.0.1',
        'PORT': '80',
    }
} 

Now we have to add this sensitive data in an environmental variable so that we have to create a file called ‘.env’ or ‘.ini’ in your project root folder.

Now add all your sensitive data in .env or .ini file and change the variable names according to settings.py file.

Check below .env files

SECRET_KEY= nizatuzy04kzvoyj1wy7)(g$&99m)-e28$h9-mjz7_$6fbp0a* 
APP_DEBUG=True
DB_NAME= demo
DB_USER=demo 
DB_PASSWORD=demo
DB_HOST=127.0.0.1
DB_PORT = 3306
ALLOWED_HOST = .localhost, .127.0.0.1

Now retrieve all your environmental variable in Setting.py 

from decouple import config, CSV
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = config('SECRET_KEY')
ALLOWED_HOSTS = config('ALLOWED_HOST', cast=Csv())
DEBUG = config('APP_DEBUG', cast=bool)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': config('DB_NAME'),
        'USER': config('DB_USER'),
        'PASSWORD': config('DB_PASSWORD'),
        'HOST': config('DB_HOST'),
        'PORT': config('DB_PORT'),
    }
} 

Casting The Data

The configuration returns the string by default. But some parameters in Django settings require values ​​such as debug must be a boolean and EMAIL_PORT must be an integer. This can be done by providing an additional parameter ‘cast’ to config so that the value is converted to the type specified before the assignment.

from decouple import config

DEBUG = config('APP_DEBUG', cast=bool)
EMAIL_PORT = config(‘EMAIL_PORT’, cast=int)

In the case of ALLOWED_HOSTS, the type should be in the list. We can also achieve this using the built-in CSV helper.

from decouple import config, CSV

ALLOWED_HOSTS = config('ALLOWED_HOST', cast=Csv())

For tuple,

CSV return list by default, but you can use the post_process argument to get a tuple format.

SECURE_PROXY_SSL_HEADER = config('SECURE_PROXY_SSL_HEADER', cast=Csv(post_process=tuple))

Default Value

If the .env file contains an undefined value, you can add additional arguments to the configuration function to define the default value.

DEBUG = config('APP_DEBUG', default=False, cast=bool)
EMAIL_PORT = config(‘EMAIL_PORT’, default=25, cast=int)

If you are developing a Django application, you must have Python decouple app to secure sensitive data in a Django. I use it in all my Django based projects. It helps to secure your application credentials, such as database details, email details, and Amazon S3 details, etc. Use only one setting.py for your entire project, except development_setting.py and production_setting.py.

I hope you understand how to secure sensitive data in a Django through this blog. See here for more information on Python decouple pypi.

Tip: If you are using Git, add this .env file to your .gitignore file. So that when you commit your code your sensitive data file will not be committed to your remote repository.

Leave a Comment