Home > Backend Development > Python Tutorial > Configuring Django project to storing sensitive data in YAML file

Configuring Django project to storing sensitive data in YAML file

Barbara Streisand
Release: 2024-12-04 18:49:12
Original
571 people have browsed it

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
Copy after login

Switch in created folder:

cd myproject
Copy after login

Create virtual environment:

python3 -m venv env
Copy after login

Activate virtual environment:

source env/bin/activate
Copy after login

Install Django and pyyaml:

pip3 install django pyyaml
Copy after login

Start new Django project:

django-admin startproject myproject .
Copy after login

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

touch myproject/settings.yaml
Copy after login

Insert imports in beginning of settings.py file:

import os
import yaml
Copy after login

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)
Copy after login

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'],
    }
}
Copy after login

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'
Copy after login

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template