Basically, many introductory articles hard-code various settings in the configuration file, but it is not good to think practically from the viewpoint of operation and security to hard-code so-called SECRET_KEY and environment variables directly. ..
So installing a module that can isolate the settings, managing it separately and loading from there is a way to avoid hard coding.
In Python, there is a module called Python-decouple, so I'll use settings.py
in Django as an example.
The project created this time can be viewed from here, so if you are interested, please.
Install and
$ pip install python-decouple
$ django-admin startproject decoupleproject
Create a project.
Since you already have Python-decouple installed, create a .env
file in the same directory as manage.py
.
And if you write the information you do not want to hard code in various configuration files in .env
and import it in sttings.py
, you can switch for each environment, which is very useful.
For example, this time
settings.py
from decouple import config
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = conig('DEBUG' default=False,cost=bool)
ALLOWED_HOSTS = config('ALLOWED_HOSTS',cost=Csv())
.env
SECRET_KEY = '6@gw!zj8jjwjr%da0g=&1dzmhjbi3p%r@6157##n0oix#&ybv2'
DEBUG = True
ALLOWED_HOSTS = []
By writing in this way, you can separate information that you do not want to be known from the outside.
There are other modules that hide database connection information, so I'd like to introduce them in the near future. Thank you for your hard work.
Recommended Posts