Automatically plug database via env vars
This commit is contained in:
parent
1064d7df1a
commit
a6f9284570
2 changed files with 34 additions and 18 deletions
29
project/database.py
Normal file
29
project/database.py
Normal file
|
@ -0,0 +1,29 @@
|
|||
import os
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
|
||||
engines = {
|
||||
'sqlite': 'django.db.backends.sqlite3',
|
||||
'postgresql': 'django.db.backends.postgresql_psycopg2',
|
||||
'mysql': 'django.db.backends.mysql',
|
||||
}
|
||||
|
||||
|
||||
def config():
|
||||
service_name = os.getenv('DATABASE_SERVICE_NAME')
|
||||
if service_name:
|
||||
engine = engines.get(os.getenv('DATABASE_ENGINE'), engines['sqlite'])
|
||||
else:
|
||||
engine = engines['sqlite']
|
||||
name = os.getenv('DATABASE_NAME')
|
||||
if not name and engine == engines['sqlite']:
|
||||
name = os.path.join(settings.BASE_DIR, 'db.sqlite3')
|
||||
return {
|
||||
'ENGINE': engine,
|
||||
'NAME': name,
|
||||
'USER': os.getenv('DATABASE_USER'),
|
||||
'PASSWORD': os.getenv('DATABASE_PASSWORD'),
|
||||
'HOST': os.getenv('{}_SERVICE_HOST'.format(service_name)),
|
||||
'PORT': os.getenv('{}_SERVICE_PORT'.format(service_name)),
|
||||
}
|
|
@ -81,23 +81,10 @@ WSGI_APPLICATION = 'project.wsgi.application'
|
|||
# Database
|
||||
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
|
||||
|
||||
if os.getenv("DATABASE_SERVICE_HOST"):
|
||||
from . import database
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.postgresql_psycopg2',
|
||||
'NAME': os.getenv("DATABASE_NAME"),
|
||||
'USER': os.getenv("DATABASE_USER"),
|
||||
'PASSWORD': os.getenv("DATABASE_PASSWORD"),
|
||||
'HOST': os.getenv("DATABASE_SERVICE_HOST"),
|
||||
'PORT': os.getenv("DATABASE_SERVICE_PORT"),
|
||||
}
|
||||
}
|
||||
else:
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
|
||||
}
|
||||
'default': database.config()
|
||||
}
|
||||
|
||||
|
||||
|
|
Loading…
Reference in a new issue