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
Switch in created folder:
cd myproject
Create virtual environment:
python3 -m venv env
Activate virtual environment:
source env/bin/activate
Install Django and pyyaml:
pip3 install django pyyaml
Start new Django project:
django-admin startproject myproject .
Create settings.yaml file near to the settings.py file:
touch myproject/settings.yaml
Insert imports in beginning of settings.py file:
import os import yaml
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)
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'], } }
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'
The above is the detailed content of Configuring Django project to storing sensitive data in YAML file. For more information, please follow other related articles on the PHP Chinese website!