DEV Community

Cover image for Configuring Django project to storing sensitive data in YAML file
Shakhzhakhan Maxudbek
Shakhzhakhan Maxudbek

Posted on • Originally published at args.tech

Configuring Django project to storing sensitive data in YAML file

Hardcoding tokens, database credentials and other sensitive data in .py files is not secure. Many people use django-environ library, but I think it inconvenient. So I use yaml files for storing sensitive data and pyyaml library for reading data of them.

Create project folder:

mkdir myproject
Enter fullscreen mode Exit fullscreen mode

Switch in created folder:

cd myproject
Enter fullscreen mode Exit fullscreen mode

Create virtual environment:

python3 -m venv env
Enter fullscreen mode Exit fullscreen mode

Activate virtual environment:

source env/bin/activate
Enter fullscreen mode Exit fullscreen mode

Install Django and pyyaml:

pip3 install django pyyaml
Enter fullscreen mode Exit fullscreen mode

Start new Django project:

django-admin startproject myproject .
Enter fullscreen mode Exit fullscreen mode

Create settings.yaml file near to the settings.py file:

touch myproject/settings.yaml
Enter fullscreen mode Exit fullscreen mode

Insert imports in beginning of settings.py file:

import os
import yaml
Enter fullscreen mode Exit fullscreen mode

Insert code for reading from settings.yaml file:

with open(os.path.join(str(Path(__file__).resolve().parent), 'settings.yaml'), 'r') as settingsfile:
    settings = yaml.safe_load(settingsfile)
Enter fullscreen mode Exit fullscreen mode

Insert code for reading from settings.yaml file:

SECRET_KEY = settings['SECRET_KEY']
DEBUG = settings['DEBUG']
ALLOWED_HOSTS = settings['ALLOWED_HOSTS']
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': settings['DATABASES']['NAME'],
        'USER': settings['DATABASES']['USER'],
        'PASSWORD': settings['DATABASES']['PASSWORD'],
        'HOST': settings['DATABASES']['HOST'],
        'PORT': settings['DATABASES']['PORT'],
    }
}
Enter fullscreen mode Exit fullscreen mode

Put configurations in settings.yaml:

SECRET_KEY: 'your-secret-token'
DEBUG: true
ALLOWED_HOSTS:
  - 127.0.0.1
  - localhost
  - 0.0.0.0
DATABASES:
  NAME: 'database_name'
  USER: 'database_user'
  PASSWORD: 'password'
  HOST: '127.0.0.1'
  PORT: '5432'
Enter fullscreen mode Exit fullscreen mode

Top comments (0)