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
Just install the library django-environ
with pip
.
pip install django-environ
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 |
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'))
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(),
}
django-environ
to reduce the management cost of settings.py..env
file.Recommended Posts