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
cd myproject
python3 -m venv env
source env/bin/activate
pip3 install django pyyaml
django-admin startproject myproject .
touch myproject/settings.yaml
import os
import yaml
with open(os.path.join(str(Path(__file__).resolve().parent), 'settings.yaml'), 'r') as settingsfile:
settings = yaml.safe_load(settingsfile)
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'],
}
}
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'