From a6f9284570a6c38d1bbb1089d5659ba89ace6e6a Mon Sep 17 00:00:00 2001 From: Rodolfo Carvalho Date: Fri, 29 May 2015 15:52:28 +0200 Subject: [PATCH] Automatically plug database via env vars --- project/database.py | 29 +++++++++++++++++++++++++++++ project/settings.py | 23 +++++------------------ 2 files changed, 34 insertions(+), 18 deletions(-) create mode 100644 project/database.py diff --git a/project/database.py b/project/database.py new file mode 100644 index 0000000..478e1da --- /dev/null +++ b/project/database.py @@ -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)), + } diff --git a/project/settings.py b/project/settings.py index b47c008..977ad19 100644 --- a/project/settings.py +++ b/project/settings.py @@ -81,24 +81,11 @@ WSGI_APPLICATION = 'project.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases -if os.getenv("DATABASE_SERVICE_HOST"): - 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'), - } - } +from . import database + +DATABASES = { + 'default': database.config() +} # Internationalization