From 4d9e15a0d9ef117870e4d075d283ccfa3f1d1ef5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Schneider?= <jschneider@entrouvert.com>
Date: Mon, 9 Feb 2015 15:03:45 +0100
Subject: [PATCH] settings: use a single settings.py file

use just HOBO_SETTINGS_FILE variable environment to set the
configuration file

Closes #6454
---
 config_example.py        |   4 +-
 hobo/default_settings.py | 157 --------------------------------------------
 hobo/settings.py         | 166 ++++++++++++++++++++++++++++++++++++++++++++---
 hobo/tenant_settings.py  |  73 ---------------------
 manage.py                |  28 +-------
 5 files changed, 160 insertions(+), 268 deletions(-)
 delete mode 100644 hobo/default_settings.py
 delete mode 100644 hobo/tenant_settings.py

diff --git a/config_example.py b/config_example.py
index c55129f..e616dd4 100644
--- a/config_example.py
+++ b/config_example.py
@@ -23,8 +23,8 @@ DATABASES = {
 # Uncomment the following lines to enable SAML support
 #INSTALLED_APPS += ('mellon',)
 #AUTHENTICATION_BACKENDS = ( 'mellon.backends.SAMLBackend',)
-#LOGIN_URL = 'mellon_login'
-#LOGOUT_URL = 'mellon_logout'
+#LOGIN_URL = '/accounts/mellon/login/'
+#LOGOUT_URL = '/accounts/mellon/logout/'
 #MELLON_PUBLIC_KEYS = ['cert.pem']
 #MELLON_PRIVATE_KEY = 'key.cert'
 #MELLON_IDENTITY_PROVIDERS = [
diff --git a/hobo/default_settings.py b/hobo/default_settings.py
deleted file mode 100644
index f041959..0000000
--- a/hobo/default_settings.py
+++ /dev/null
@@ -1,157 +0,0 @@
-"""
-Django settings for hobo project.
-
-For more information on this file, see
-https://docs.djangoproject.com/en/1.6/topics/settings/
-
-For the full list of settings and their values, see
-https://docs.djangoproject.com/en/1.6/ref/settings/
-"""
-
-from django.conf import global_settings
-
-# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
-import os
-BASE_DIR = os.path.dirname(os.path.dirname(__file__))
-
-
-# Quick-start development settings - unsuitable for production
-# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
-
-# SECURITY WARNING: keep the secret key used in production secret!
-SECRET_KEY = 'hc^g)m7+*n+!8ej5i4*5iiv21s-y#+lpgje1w8d1jw5cyd+g%s'
-
-# SECURITY WARNING: don't run with debug turned on in production!
-DEBUG = True
-
-TEMPLATE_DEBUG = True
-
-ALLOWED_HOSTS = []
-
-
-# Application definition
-
-INSTALLED_APPS = (
-    'django.contrib.admin',
-    'django.contrib.auth',
-    'django.contrib.contenttypes',
-    'django.contrib.sessions',
-    'django.contrib.messages',
-    'django.contrib.staticfiles',
-    'gadjo',
-    'hobo.environment',
-    'hobo.agent',
-)
-
-MIDDLEWARE_CLASSES = (
-    'django.contrib.sessions.middleware.SessionMiddleware',
-    'django.middleware.locale.LocaleMiddleware',
-    'django.middleware.common.CommonMiddleware',
-    'django.middleware.csrf.CsrfViewMiddleware',
-    'django.contrib.auth.middleware.AuthenticationMiddleware',
-    'django.contrib.messages.middleware.MessageMiddleware',
-    'django.middleware.clickjacking.XFrameOptionsMiddleware',
-)
-
-ROOT_URLCONF = 'hobo.urls'
-
-WSGI_APPLICATION = 'hobo.wsgi.application'
-
-
-# Database
-# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
-
-DATABASES = {
-    'default': {
-        'ENGINE': 'django.db.backends.sqlite3',
-        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
-    }
-}
-
-# Internationalization
-# https://docs.djangoproject.com/en/1.6/topics/i18n/
-
-LANGUAGE_CODE = 'en-us'
-
-TIME_ZONE = 'UTC'
-
-USE_I18N = True
-
-USE_L10N = True
-
-USE_TZ = True
-
-
-# Static files (CSS, JavaScript, Images)
-# https://docs.djangoproject.com/en/1.6/howto/static-files/
-
-STATIC_URL = '/static/'
-STATIC_ROOT = os.path.join(BASE_DIR, 'static')
-
-TEMPLATE_DIRS = (
-    os.path.join(BASE_DIR, 'hobo', 'templates'),
-)
-
-STATICFILES_FINDERS = global_settings.STATICFILES_FINDERS + ('gadjo.finders.XStaticFinder',)
-
-STATICFILES_DIRS = (
-    os.path.join(BASE_DIR, 'hobo', 'static'),
-)
-
-LOCALE_PATHS = (
-    os.path.join(BASE_DIR, 'hobo', 'locale'),
-)
-
-SERVICE_URL_TEMPLATE = 'https://${app}.example.net'
-
-# SERVICE_TEMPLATES: possible "flavours" for the various service types.
-# This variable expects a dictionary mapping service identifiers
-# to a list of (template name, template title) tuples.
-#
-# Note: Template names are opaque identifiers, it's up to the deployment
-# agents to assign some meaning to them.
-#
-# Example:
-#    SERVICE_TEMPLATES = {
-#        'wcs': [('export-auquo-light.wcs', u'Au quotidien light'),
-#                ('export-auquo.wcs', u'Au quotidien'),
-#                ('export-demo.wcs', u'Au quotidien Demo')],
-#    }
-SERVICE_TEMPLATES = None
-
-# SERVICE_EXTRA_VARIABLES: variables to create automatically for the
-# given service types.
-#
-# Example:
-#    SERVICE_EXTRA_VARIABLES = {
-#        'wcs': ['legal_url', 'commune_url', 'domain_key'],
-#    }
-SERVICE_EXTRA_VARIABLES = None
-
-AGENT_HOST_PATTERNS = None
-AGENT_WCS_COMMAND = '/usr/sbin/wcsctl check-hobos'
-AGENT_AUTHENTIC_COMMAND = '/usr/bin/authentic2-ctl deploy'
-
-try:
-    from kombu.common import Broadcast
-    CELERY_ACCEPT_CONTENT = ['json']
-    CELERY_TASK_SERIALIZER = 'json'
-    CELERY_QUEUES = (Broadcast('broadcast_tasks'), )
-except ImportError:
-    pass
-
-LOGIN_REDIRECT_URL = '/'
-
-# mellon authentication params
-MELLON_ATTRIBUTE_MAPPING = {
-    'username': '{attributes[username][0]}',
-    'email': '{attributes[email][0]}',
-    'first_name': '{attributes[first_name][0]}',
-    'last_name': '{attributes[last_name][0]}',
-}
-
-MELLON_SUPERUSER_MAPPING = {
-    'roles': 'Admin::Hobo',
-}
-
-MELLON_USERNAME_TEMPLATE = '{attributes[username][0]}'
diff --git a/hobo/settings.py b/hobo/settings.py
index 943852e..084972e 100644
--- a/hobo/settings.py
+++ b/hobo/settings.py
@@ -1,15 +1,161 @@
-from django.conf.global_settings import *
-from hobo.default_settings import *
-from django.core.exceptions import ImproperlyConfigured
+"""
+Django settings file; it loads the default settings, and local settings
+(from a local_settings.py file, or a configuration file set in the
+HOBO_SETTINGS_FILE environment variable).
+
+The local settings file should exist, at least to set a suitable SECRET_KEY,
+and to disable DEBUG mode in production.
+"""
 
 import os
-import logging
+from django.conf import global_settings
+
+# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
+BASE_DIR = os.path.dirname(os.path.dirname(__file__))
+
+
+# Quick-start development settings - unsuitable for production
+# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
+
+# SECURITY WARNING: keep the secret key used in production secret!
+SECRET_KEY = 'hc^g)m7+*n+!8ej5i4*5iiv21s-y#+lpgje1w8d1jw5cyd+g%s'
+
+# SECURITY WARNING: don't run with debug turned on in production!
+DEBUG = True
+
+TEMPLATE_DEBUG = True
+
+ALLOWED_HOSTS = []
+
+
+# Application definition
+
+INSTALLED_APPS = (
+    'django.contrib.admin',
+    'django.contrib.auth',
+    'django.contrib.contenttypes',
+    'django.contrib.sessions',
+    'django.contrib.messages',
+    'django.contrib.staticfiles',
+    'gadjo',
+    'hobo.environment',
+    'hobo.agent',
+)
+
+MIDDLEWARE_CLASSES = (
+    'django.contrib.sessions.middleware.SessionMiddleware',
+    'django.middleware.locale.LocaleMiddleware',
+    'django.middleware.common.CommonMiddleware',
+    'django.middleware.csrf.CsrfViewMiddleware',
+    'django.contrib.auth.middleware.AuthenticationMiddleware',
+    'django.contrib.messages.middleware.MessageMiddleware',
+    'django.middleware.clickjacking.XFrameOptionsMiddleware',
+)
+
+ROOT_URLCONF = 'hobo.urls'
+
+WSGI_APPLICATION = 'hobo.wsgi.application'
+
+
+# Database
+# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
+
+DATABASES = {
+    'default': {
+        'ENGINE': 'django.db.backends.sqlite3',
+        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
+    }
+}
+
+# Internationalization
+# https://docs.djangoproject.com/en/1.6/topics/i18n/
+
+LANGUAGE_CODE = 'en-us'
+
+TIME_ZONE = 'UTC'
+
+USE_I18N = True
+
+USE_L10N = True
+
+USE_TZ = True
+
+
+# Static files (CSS, JavaScript, Images)
+# https://docs.djangoproject.com/en/1.6/howto/static-files/
+
+STATIC_URL = '/static/'
+STATIC_ROOT = os.path.join(BASE_DIR, 'static')
+
+TEMPLATE_DIRS = (
+    os.path.join(BASE_DIR, 'hobo', 'templates'),
+)
+
+STATICFILES_FINDERS = global_settings.STATICFILES_FINDERS + ('gadjo.finders.XStaticFinder',)
+
+STATICFILES_DIRS = (
+    os.path.join(BASE_DIR, 'hobo', 'static'),
+)
+
+LOCALE_PATHS = (
+    os.path.join(BASE_DIR, 'hobo', 'locale'),
+)
+
+SERVICE_URL_TEMPLATE = 'https://${app}.example.net'
+
+# SERVICE_TEMPLATES: possible "flavours" for the various service types.
+# This variable expects a dictionary mapping service identifiers
+# to a list of (template name, template title) tuples.
+#
+# Note: Template names are opaque identifiers, it's up to the deployment
+# agents to assign some meaning to them.
+#
+# Example:
+#    SERVICE_TEMPLATES = {
+#        'wcs': [('export-auquo-light.wcs', u'Au quotidien light'),
+#                ('export-auquo.wcs', u'Au quotidien'),
+#                ('export-demo.wcs', u'Au quotidien Demo')],
+#    }
+SERVICE_TEMPLATES = None
+
+# SERVICE_EXTRA_VARIABLES: variables to create automatically for the
+# given service types.
+#
+# Example:
+#    SERVICE_EXTRA_VARIABLES = {
+#        'wcs': ['legal_url', 'commune_url', 'domain_key'],
+#    }
+SERVICE_EXTRA_VARIABLES = None
+
+AGENT_HOST_PATTERNS = None
+AGENT_WCS_COMMAND = '/usr/sbin/wcsctl check-hobos'
+AGENT_AUTHENTIC_COMMAND = '/usr/bin/authentic2-ctl deploy'
+
+try:
+    from kombu.common import Broadcast
+    CELERY_ACCEPT_CONTENT = ['json']
+    CELERY_TASK_SERIALIZER = 'json'
+    CELERY_QUEUES = (Broadcast('broadcast_tasks'), )
+except ImportError:
+    pass
+
+LOGIN_REDIRECT_URL = '/'
+
+# mellon authentication params
+MELLON_ATTRIBUTE_MAPPING = {
+    'username': '{attributes[username][0]}',
+    'email': '{attributes[email][0]}',
+    'first_name': '{attributes[first_name][0]}',
+    'last_name': '{attributes[last_name][0]}',
+}
 
-if 'DJANGO_CONFIG_FILE' in os.environ:
-    logging.getLogger('hobo').debug('Loading setting file %r', os.environ['DJANGO_CONFIG_FILE'])
-    execfile(os.environ['DJANGO_CONFIG_FILE'])
+MELLON_SUPERUSER_MAPPING = {
+    'roles': 'Admin::Hobo',
+}
 
-if 'DATABASES' not in globals():
-    logging.getLogger('hobo').error('Unable to boot: You must define a DATABASES in your settings')
-    raise ImproperlyConfigured('You must define a DATABASES variable in your settings')
+MELLON_USERNAME_TEMPLATE = '{attributes[username][0]}'
 
+local_settings_file = os.environ.get('HOBO_SETTINGS_FILE',
+        os.path.join(os.path.dirname(__file__), 'local_settings.py'))
+if os.path.exists(local_settings_file):
+    execfile(local_settings_file)
diff --git a/hobo/tenant_settings.py b/hobo/tenant_settings.py
deleted file mode 100644
index 8ada082..0000000
--- a/hobo/tenant_settings.py
+++ /dev/null
@@ -1,73 +0,0 @@
-from django.conf.global_settings import *
-from hobo.default_settings import *
-from django.core.exceptions import ImproperlyConfigured
-
-import os
-import logging
-
-try:
-    import entrouvert
-except ImportError:
-    raise ImproperlyConfigured('python-entrouvert MUST be installed for the multitenant mode to work')
-
-DATABASES = {
-    'default': {
-        'ENGINE': 'django.db.backends.postgresql_psycopg2',
-        'NAME': 'portail_admin',
-    },
-}
-
-TENANT_BASE = None
-TENANT_TEMPLATE_DIRS = ( TENANT_BASE, )
-TENANT_MODEL = 'multitenant.Tenant'
-
-SOUTH_TESTS_MIGRATE = False
-SOUTH_DATABASE_ADAPTERS = {
-    'default': 'south.db.postgresql_psycopg2',
-}
-
-DEFAULT_FILE_STORAGE = 'entrouvert.djommon.multitenant.storage.TenantFileSystemStorage'
-
-MIDDLEWARE_CLASSES = (
-        'entrouvert.djommon.multitenant.middleware.TenantMiddleware',
-        'entrouvert.djommon.multitenant.middleware.JSONSettingsMiddleware',
-        'entrouvert.djommon.multitenant.middleware.PythonSettingsMiddleware',
-) + MIDDLEWARE_CLASSES
-
-
-TEMPLATE_LOADERS = (
-    'entrouvert.djommon.multitenant.template_loader.FilesystemLoader',
-    'django.template.loaders.filesystem.Loader',
-    'django.template.loaders.app_directories.Loader',
-)
-
-PUBLIC_SCHEMA_URLCONF = 'hobo.manager_urls'
-
-SHARED_APPS = (
-    'django.contrib.auth',
-    'django.contrib.contenttypes',
-    'django.contrib.sessions',
-    'django.contrib.messages',
-    'django.contrib.staticfiles',
-    'django.contrib.admin',
-)
-
-INSTALLED_APPS = INSTALLED_APPS + ('entrouvert.djommon.multitenant',)
-TENANT_APPS = INSTALLED_APPS
-
-if 'DJANGO_CONFIG_FILE' in os.environ:
-    logging.getLogger('hobo').debug('Loading setting file %r', os.environ['DJANGO_CONFIG_FILE'])
-    execfile(os.environ['DJANGO_CONFIG_FILE'])
-
-if not TENANT_BASE:
-    logging.getLogger('hobo').error('Unable to boot: You must define a TENANT_BASE in your settings')
-    raise ImproperlyConfigured('You must define a TENANT_BASE in your settings')
-
-if 'DATABASES' not in globals():
-    logging.getLogger('hobo').error('Unable to boot: You must define a DATABASES in your settings')
-    raise ImproperlyConfigured('You must define a DATABASES variable in your settings')
-
-if DATABASES['default']['ENGINE'] != 'django.db.backends.postgresql_psycopg2':
-    raise ImproperlyConfigured('MULTITENANT only work with django.db.backends.postgresql_psycopg2 Django db backend')
-DATABASES['default']['ENGINE'] = 'tenant_schemas.postgresql_backend'
-
diff --git a/manage.py b/manage.py
index b103685..c84d3a0 100755
--- a/manage.py
+++ b/manage.py
@@ -3,32 +3,8 @@ import os
 import sys
 
 if __name__ == "__main__":
-    multitenant = False
-    config_file = False
-
-    argv = sys.argv[1:]
-    for arg in list(argv):
-        if arg.startswith('--'):
-            if arg.startswith('--config='):
-                config_file = arg.split('=')[1]
-                argv.pop(0)
-            elif arg == '--multitenant':
-                multitenant = True
-                argv.pop(0)
-            else:
-                print >>sys.stderr, 'ERR: Unsupported flag', arg
-                sys.exit(1)
-        else:
-            break
-
-    if config_file:
-        os.environ['DJANGO_CONFIG_FILE'] = config_file
-
-    if multitenant:
-        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hobo.tenant_settings")
-    else:
-        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hobo.settings")
+    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hobo.settings")
 
     from django.core.management import execute_from_command_line
 
-    execute_from_command_line(sys.argv[:1] + argv)
+    execute_from_command_line(sys.argv)
-- 
2.1.4

