[PYTHON] Switch the setting value of setting.py according to the development environment

Overview

When using something other than SQLite with Django, you need to be careful when managing it on Github because the DB connection information is included in settings.py. Also, since the connection destination changes depending on the development environment, it is troublesome to create settings.py for each connection destination. All files must be updated if there is a change other than the connection destination.

After a lot of research, I found a library called django-environ. You can store settings such as the DB connection destination in system environment variables when Django starts, and set the system environment variables stored when loading settings.py in fields such as ALLOWED_HOSTS. It is a library that was created to eliminate the hassle of managing settings.py. Official site is good, but the following site was very easy to understand, so I will summarize the procedure to install django-environ.

Quote: Try managing environment variables with django-environ

Introduction method

  1. Library installation
  2. Creating an environment variable definition file
  3. Incorporate into settings.py

Step 1

Just install the library django-environ with pip.

pip install django-environ

Step 2

Create an environment variable definition file. Name the file .env and create it in the same directory ** as ** manage.py. The reason for creating it in the same directory as manage.py will be described later in step 3.

djnago project
├── manage.py
├── .env
└── xxxx
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py

In the .env file, define system-specific information such as ALLOWED_HOSTS and DATABASES that was defined in settings.py in the key = value format. When using a DB other than SQLite, it is necessary to set a user name and password in DATABASES, but if you write it in DATABASE_URL, you can write it in one line. When defining multiple host names in ALLOWED_HOSTS, separate them with commas. Below, the items required to switch between the development environment and the production environment are defined.

.env


SECRET_KEY=aiueo
DEBUG=True
ALLOWED_HOSTS=
DATABASE_URL=mysql://USER:PASSWORD@HOST:PORT/NAME

The description method of DATABASE_URL in each database is as follows.

Engine Django Backend URL
PostgreSQL django.db.backends.postgresql_psycopg2 postgres://USER:PASSWORD@HOST:PORT/NAME
PostGIS django.contrib.gis.db.backends.postgis postgis://USER:PASSWORD@HOST:PORT/NAME
MSSQL sql_server.pyodbc mssql://USER:PASSWORD@HOST:PORT/NAME
MySQL django.db.backends.mysql mysql://USER:PASSWORD@HOST:PORT/NAME
MySQL (GIS) django.contrib.gis.db.backends.mysql mysqlgis://USER:PASSWORD@HOST:PORT/NAME
SQLite django.db.backends.sqlite3 sqlite:///PATH
SpatiaLite django.contrib.gis.db.backends.spatialite spatialite:///PATH
Oracle django.db.backends.oracle oracle://USER:PASSWORD@HOST:PORT/NAME
Oracle (GIS) django.contrib.gis.db.backends.oracle oraclegis://USER:PASSWORD@HOST:PORT/NAME
Redshift django_redshift_backend redshift://USER:PASSWORD@HOST:PORT/NAME

Step 3

Read .env file

Read the setting information in the .env file with settings.py. Below, the .env file in BASE_DIR is read. If you place the .env file in a different directory than manage.py, you need to specify the directory.

settings.py


import environ

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

env = environ.Env(DEBUG=(bool,True))
env.read_env(os.path.join(BASE_DIR,'.env'))

How to set each field

All you have to do is specify the key name you want to get and get the settings in the .env file. The set value is stored in the Env class and can be referenced in a dictionary type. Note that if you specify a key that does not exist, a KeyError will occur. This area has the same specifications as ʻos.environ`.

You can also get it with a function called get_value. With get_value, KeyError does not occur even if the key does not exist, and the return value can be specified as an argument. You can also specify the return type.

Env.get_value(var, cast=None, default=NOTSET, parse_default=False) -> float

ALLOWED_HOSTS uses a function that returns a list type, given that multiple host names are defined. The user name and password to connect to the DB were individually defined in the'default'of DATABASES, but when the function of .db () is used, the contents of DATABASE_URL are converted to a list type that can be read by'default'. It's very convenient because it does.

settings.py


SECRET_KEY = env.get_value('SECRET_KEY',str)

DEBUG = env.get_value('DEBUG', bool)

ALLOWED_HOSTS = env.list('ALLOWED_HOSTS')

SESSION_COOKIE_AGE = env.get_value('SESSION_COOKIE_AGE', int) #Session validity period (seconds)

DATABASES = {
    'default':env.db(),
}

Summary

Recommended Posts

Switch the setting value of setting.py according to the development environment
Change the volume of Pepper according to the surrounding environment (sound)
How to set up the development environment of ev3dev [Windows version]
Introduction to Python Let's prepare the development environment
Setting to output the log of cron execution
Instantiation of the BOX development environment created earlier
[C language] [Linux] Get the value of environment variable
Link the mouse to the gyro of the Nintendo Switch Procon
Ssh to virtual environment with remote development of vscode
Automatically select BGM according to the content of the conversation
Unify the environment of the Python development team starting with Poetry
Pros and cons of converting Django's development environment to Docker
Dot according to the image
Inherit the standard library to find the average value of Queue
Django + MongoDB development environment maintenance (in the middle of writing)
How to get into the python development environment with Vagrant
How to handle multiple versions of CUDA in the same environment
Django cannot be installed in the development environment of pipenv + pyenv
Switch the package to be installed for each environment with poetry
LINEbot development, I want to check the operation in the local environment
How to find the memory address of a Pandas dataframe value
Using TensorFlow in the cloud integrated development environment Cloud9 ~ Basics of usage ~
Periodically log the value of Omron environment sensor with Raspberry Pi
Find the definition of the value of errno
About the return value of pthread_mutex_init ()
About the return value of the histogram.
Vim + Python development environment setting memo
Checking the NAOqi Python development environment
Supplement to the explanation of vscode
Prepare the development environment with anyenv
Use Cloud Dataflow to dynamically change the destination according to the value of the data and save it in GCS
[Golang Error handling] The best way to separate processing according to the type of error
How to easily switch the virtual environment created by Conda on Jupyter
I measured 6 methods to get the index of the maximum value (minimum value) of the list
Setting to debug test by entering the contents of the library with pytest
[Development environment] How to create a data set close to the production DB
Logging the value of Omron environment sensor with Raspberry Pi (USB type)
Switch the module to be loaded for each execution environment in Python
I tried to display the altitude value of DTM in a graph
The story of trying to reconnect the client
Addition of local development environment on MacOS
Script to change the description of fasta
10 methods to improve the accuracy of BERT
How to check the version of Django
The story of adding MeCab to ubuntu 16.04
About the virtual environment of python version 3.7
How to prepare Python development environment [Mac]
Build the execution environment of Jupyter Lab
Use numpy's .flatten () [0] to retrieve the value
Try to prepare each environment of kivy
About the development environment you are using
LightGBM predict contributes to the predicted value
Prepare the development environment for keyhac for Mac
Get the value of the middle layer of NN
Construction of development environment for Choreonoid class
The story of pep8 changing to pycodestyle
The strongest Python development environment PyCharm's recommendation
The strongest Python integrated development environment PyCharm
Make the default value of the argument immutable
How to make VS Code aware of the venv environment and its benefits
Test of the difference between the mean values of count data according to the Poisson distribution