Automatically plug database via env vars

This commit is contained in:
Rodolfo Carvalho 2015-05-29 15:52:28 +02:00
parent 1064d7df1a
commit a6f9284570
2 changed files with 34 additions and 18 deletions

29
project/database.py Normal file
View 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)),
}

View file

@ -81,24 +81,11 @@ WSGI_APPLICATION = 'project.wsgi.application'
# Database # Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases # https://docs.djangoproject.com/en/1.8/ref/settings/#databases
if os.getenv("DATABASE_SERVICE_HOST"): from . import database
DATABASES = {
'default': { DATABASES = {
'ENGINE': 'django.db.backends.postgresql_psycopg2', 'default': database.config()
'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'),
}
}
# Internationalization # Internationalization