Projet

Général

Profil

0001-settings-use-a-single-settings.py-file.patch

Jérôme Schneider, 09 février 2015 15:09

Télécharger (16,6 ko)

Voir les différences:

Subject: [PATCH] settings: use a single settings.py file

use just HOBO_SETTINGS_FILE variable environment to set the
configuration file

Closes #6454
 config_multitenant_example.py |  78 ++++++++++++++++++++
 hobo/default_settings.py      | 157 ----------------------------------------
 hobo/settings.py              | 165 +++++++++++++++++++++++++++++++++++++++---
 hobo/tenant_settings.py       |  73 -------------------
 manage.py                     |  28 +------
 5 files changed, 235 insertions(+), 266 deletions(-)
 create mode 100644 config_multitenant_example.py
 delete mode 100644 hobo/default_settings.py
 delete mode 100644 hobo/tenant_settings.py
config_multitenant_example.py
1
from django.core.exceptions import ImproperlyConfigured
2

  
3
import os
4
import logging
5

  
6
try:
7
    import entrouvert
8
except ImportError:
9
    raise ImproperlyConfigured('python-entrouvert MUST be installed for the multitenant mode to work')
10

  
11
DATABASES = {
12
    'default': {
13
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
14
        'NAME': 'portail_admin',
15
    },
16
}
17

  
18
DEBUG = True
19

  
20
SECRET_KEY = 'changeme'
21

  
22
MEDIA_ROOT = 'media'
23
STATIC_ROOT = 'collected-static'
24

  
25
TENANT_BASE = "/var/lib/hobo/tenants"
26
TENANT_TEMPLATE_DIRS = ( TENANT_BASE, )
27
TENANT_MODEL = 'multitenant.Tenant'
28

  
29
SOUTH_TESTS_MIGRATE = False
30
SOUTH_DATABASE_ADAPTERS = {
31
    'default': 'south.db.postgresql_psycopg2',
32
}
33

  
34
DEFAULT_FILE_STORAGE = 'entrouvert.djommon.multitenant.storage.TenantFileSystemStorage'
35

  
36
MIDDLEWARE_CLASSES = (
37
        'entrouvert.djommon.multitenant.middleware.TenantMiddleware',
38
        'entrouvert.djommon.multitenant.middleware.JSONSettingsMiddleware',
39
        'entrouvert.djommon.multitenant.middleware.PythonSettingsMiddleware',
40
) + MIDDLEWARE_CLASSES
41

  
42

  
43
TEMPLATE_LOADERS = (
44
    'entrouvert.djommon.multitenant.template_loader.FilesystemLoader',
45
    'django.template.loaders.filesystem.Loader',
46
    'django.template.loaders.app_directories.Loader',
47
)
48

  
49
PUBLIC_SCHEMA_URLCONF = 'hobo.manager_urls'
50

  
51
SHARED_APPS = (
52
    'django.contrib.auth',
53
    'django.contrib.contenttypes',
54
    'django.contrib.sessions',
55
    'django.contrib.messages',
56
    'django.contrib.staticfiles',
57
    'django.contrib.admin',
58
)
59

  
60
INSTALLED_APPS = INSTALLED_APPS + ('entrouvert.djommon.multitenant',)
61
TENANT_APPS = INSTALLED_APPS
62

  
63
if 'DJANGO_CONFIG_FILE' in os.environ:
64
    logging.getLogger('hobo').debug('Loading setting file %r', os.environ['DJANGO_CONFIG_FILE'])
65
    execfile(os.environ['DJANGO_CONFIG_FILE'])
66

  
67
if not TENANT_BASE:
68
    logging.getLogger('hobo').error('Unable to boot: You must define a TENANT_BASE in your settings')
69
    raise ImproperlyConfigured('You must define a TENANT_BASE in your settings')
70

  
71
if 'DATABASES' not in globals():
72
    logging.getLogger('hobo').error('Unable to boot: You must define a DATABASES in your settings')
73
    raise ImproperlyConfigured('You must define a DATABASES variable in your settings')
74

  
75
if DATABASES['default']['ENGINE'] != 'django.db.backends.postgresql_psycopg2':
76
    raise ImproperlyConfigured('MULTITENANT only work with django.db.backends.postgresql_psycopg2 Django db backend')
77
DATABASES['default']['ENGINE'] = 'tenant_schemas.postgresql_backend'
78

  
hobo/default_settings.py
1
"""
2
Django settings for hobo project.
3

  
4
For more information on this file, see
5
https://docs.djangoproject.com/en/1.6/topics/settings/
6

  
7
For the full list of settings and their values, see
8
https://docs.djangoproject.com/en/1.6/ref/settings/
9
"""
10

  
11
from django.conf import global_settings
12

  
13
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
14
import os
15
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
16

  
17

  
18
# Quick-start development settings - unsuitable for production
19
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
20

  
21
# SECURITY WARNING: keep the secret key used in production secret!
22
SECRET_KEY = 'hc^g)m7+*n+!8ej5i4*5iiv21s-y#+lpgje1w8d1jw5cyd+g%s'
23

  
24
# SECURITY WARNING: don't run with debug turned on in production!
25
DEBUG = True
26

  
27
TEMPLATE_DEBUG = True
28

  
29
ALLOWED_HOSTS = []
30

  
31

  
32
# Application definition
33

  
34
INSTALLED_APPS = (
35
    'django.contrib.admin',
36
    'django.contrib.auth',
37
    'django.contrib.contenttypes',
38
    'django.contrib.sessions',
39
    'django.contrib.messages',
40
    'django.contrib.staticfiles',
41
    'gadjo',
42
    'hobo.environment',
43
    'hobo.agent',
44
)
45

  
46
MIDDLEWARE_CLASSES = (
47
    'django.contrib.sessions.middleware.SessionMiddleware',
48
    'django.middleware.locale.LocaleMiddleware',
49
    'django.middleware.common.CommonMiddleware',
50
    'django.middleware.csrf.CsrfViewMiddleware',
51
    'django.contrib.auth.middleware.AuthenticationMiddleware',
52
    'django.contrib.messages.middleware.MessageMiddleware',
53
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
54
)
55

  
56
ROOT_URLCONF = 'hobo.urls'
57

  
58
WSGI_APPLICATION = 'hobo.wsgi.application'
59

  
60

  
61
# Database
62
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
63

  
64
DATABASES = {
65
    'default': {
66
        'ENGINE': 'django.db.backends.sqlite3',
67
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
68
    }
69
}
70

  
71
# Internationalization
72
# https://docs.djangoproject.com/en/1.6/topics/i18n/
73

  
74
LANGUAGE_CODE = 'en-us'
75

  
76
TIME_ZONE = 'UTC'
77

  
78
USE_I18N = True
79

  
80
USE_L10N = True
81

  
82
USE_TZ = True
83

  
84

  
85
# Static files (CSS, JavaScript, Images)
86
# https://docs.djangoproject.com/en/1.6/howto/static-files/
87

  
88
STATIC_URL = '/static/'
89
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
90

  
91
TEMPLATE_DIRS = (
92
    os.path.join(BASE_DIR, 'hobo', 'templates'),
93
)
94

  
95
STATICFILES_FINDERS = global_settings.STATICFILES_FINDERS + ('gadjo.finders.XStaticFinder',)
96

  
97
STATICFILES_DIRS = (
98
    os.path.join(BASE_DIR, 'hobo', 'static'),
99
)
100

  
101
LOCALE_PATHS = (
102
    os.path.join(BASE_DIR, 'hobo', 'locale'),
103
)
104

  
105
SERVICE_URL_TEMPLATE = 'https://${app}.example.net'
106

  
107
# SERVICE_TEMPLATES: possible "flavours" for the various service types.
108
# This variable expects a dictionary mapping service identifiers
109
# to a list of (template name, template title) tuples.
110
#
111
# Note: Template names are opaque identifiers, it's up to the deployment
112
# agents to assign some meaning to them.
113
#
114
# Example:
115
#    SERVICE_TEMPLATES = {
116
#        'wcs': [('export-auquo-light.wcs', u'Au quotidien light'),
117
#                ('export-auquo.wcs', u'Au quotidien'),
118
#                ('export-demo.wcs', u'Au quotidien Demo')],
119
#    }
120
SERVICE_TEMPLATES = None
121

  
122
# SERVICE_EXTRA_VARIABLES: variables to create automatically for the
123
# given service types.
124
#
125
# Example:
126
#    SERVICE_EXTRA_VARIABLES = {
127
#        'wcs': ['legal_url', 'commune_url', 'domain_key'],
128
#    }
129
SERVICE_EXTRA_VARIABLES = None
130

  
131
AGENT_HOST_PATTERNS = None
132
AGENT_WCS_COMMAND = '/usr/sbin/wcsctl check-hobos'
133
AGENT_AUTHENTIC_COMMAND = '/usr/bin/authentic2-ctl deploy'
134

  
135
try:
136
    from kombu.common import Broadcast
137
    CELERY_ACCEPT_CONTENT = ['json']
138
    CELERY_TASK_SERIALIZER = 'json'
139
    CELERY_QUEUES = (Broadcast('broadcast_tasks'), )
140
except ImportError:
141
    pass
142

  
143
LOGIN_REDIRECT_URL = '/'
144

  
145
# mellon authentication params
146
MELLON_ATTRIBUTE_MAPPING = {
147
    'username': '{attributes[username][0]}',
148
    'email': '{attributes[email][0]}',
149
    'first_name': '{attributes[first_name][0]}',
150
    'last_name': '{attributes[last_name][0]}',
151
}
152

  
153
MELLON_SUPERUSER_MAPPING = {
154
    'roles': 'Admin::Hobo',
155
}
156

  
157
MELLON_USERNAME_TEMPLATE = '{attributes[username][0]}'
hobo/settings.py
1
from django.conf.global_settings import *
2
from hobo.default_settings import *
3
from django.core.exceptions import ImproperlyConfigured
1
"""
2
Django settings file; it loads the default settings, and local settings
3
(from a local_settings.py file, or a configuration file set in the
4
HOBO_SETTINGS_FILE environment variable).
5

  
6
The local settings file should exist, at least to set a suitable SECRET_KEY,
7
and to disable DEBUG mode in production.
8
"""
4 9

  
5 10
import os
6
import logging
11
from django.conf import global_settings
12

  
13
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
14
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
15

  
16

  
17
# Quick-start development settings - unsuitable for production
18
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
19

  
20
# SECURITY WARNING: keep the secret key used in production secret!
21
SECRET_KEY = 'hc^g)m7+*n+!8ej5i4*5iiv21s-y#+lpgje1w8d1jw5cyd+g%s'
22

  
23
# SECURITY WARNING: don't run with debug turned on in production!
24
DEBUG = True
25

  
26
TEMPLATE_DEBUG = True
27

  
28
ALLOWED_HOSTS = []
29

  
30

  
31
# Application definition
32

  
33
INSTALLED_APPS = (
34
    'django.contrib.admin',
35
    'django.contrib.auth',
36
    'django.contrib.contenttypes',
37
    'django.contrib.sessions',
38
    'django.contrib.messages',
39
    'django.contrib.staticfiles',
40
    'gadjo',
41
    'hobo.environment',
42
    'hobo.agent',
43
)
44

  
45
MIDDLEWARE_CLASSES = (
46
    'django.contrib.sessions.middleware.SessionMiddleware',
47
    'django.middleware.locale.LocaleMiddleware',
48
    'django.middleware.common.CommonMiddleware',
49
    'django.middleware.csrf.CsrfViewMiddleware',
50
    'django.contrib.auth.middleware.AuthenticationMiddleware',
51
    'django.contrib.messages.middleware.MessageMiddleware',
52
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
53
)
54

  
55
ROOT_URLCONF = 'hobo.urls'
56

  
57
WSGI_APPLICATION = 'hobo.wsgi.application'
58

  
59

  
60
# Database
61
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
62

  
63
DATABASES = {
64
    'default': {
65
        'ENGINE': 'django.db.backends.sqlite3',
66
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
67
    }
68
}
69

  
70
# Internationalization
71
# https://docs.djangoproject.com/en/1.6/topics/i18n/
72

  
73
LANGUAGE_CODE = 'en-us'
74

  
75
TIME_ZONE = 'UTC'
76

  
77
USE_I18N = True
78

  
79
USE_L10N = True
80

  
81
USE_TZ = True
82

  
83

  
84
# Static files (CSS, JavaScript, Images)
85
# https://docs.djangoproject.com/en/1.6/howto/static-files/
86

  
87
STATIC_URL = '/static/'
88
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
89

  
90
TEMPLATE_DIRS = (
91
    os.path.join(BASE_DIR, 'hobo', 'templates'),
92
)
93

  
94
STATICFILES_FINDERS = global_settings.STATICFILES_FINDERS + ('gadjo.finders.XStaticFinder',)
95

  
96
STATICFILES_DIRS = (
97
    os.path.join(BASE_DIR, 'hobo', 'static'),
98
)
99

  
100
LOCALE_PATHS = (
101
    os.path.join(BASE_DIR, 'hobo', 'locale'),
102
)
103

  
104
SERVICE_URL_TEMPLATE = 'https://${app}.example.net'
105

  
106
# SERVICE_TEMPLATES: possible "flavours" for the various service types.
107
# This variable expects a dictionary mapping service identifiers
108
# to a list of (template name, template title) tuples.
109
#
110
# Note: Template names are opaque identifiers, it's up to the deployment
111
# agents to assign some meaning to them.
112
#
113
# Example:
114
#    SERVICE_TEMPLATES = {
115
#        'wcs': [('export-auquo-light.wcs', u'Au quotidien light'),
116
#                ('export-auquo.wcs', u'Au quotidien'),
117
#                ('export-demo.wcs', u'Au quotidien Demo')],
118
#    }
119
SERVICE_TEMPLATES = None
120

  
121
# SERVICE_EXTRA_VARIABLES: variables to create automatically for the
122
# given service types.
123
#
124
# Example:
125
#    SERVICE_EXTRA_VARIABLES = {
126
#        'wcs': ['legal_url', 'commune_url', 'domain_key'],
127
#    }
128
SERVICE_EXTRA_VARIABLES = None
129

  
130
AGENT_HOST_PATTERNS = None
131
AGENT_WCS_COMMAND = '/usr/sbin/wcsctl check-hobos'
132
AGENT_AUTHENTIC_COMMAND = '/usr/bin/authentic2-ctl deploy'
133

  
134
try:
135
    from kombu.common import Broadcast
136
    CELERY_ACCEPT_CONTENT = ['json']
137
    CELERY_TASK_SERIALIZER = 'json'
138
    CELERY_QUEUES = (Broadcast('broadcast_tasks'), )
139
except ImportError:
140
    pass
141

  
142
LOGIN_REDIRECT_URL = '/'
143

  
144
# mellon authentication params
145
MELLON_ATTRIBUTE_MAPPING = {
146
    'username': '{attributes[username][0]}',
147
    'email': '{attributes[email][0]}',
148
    'first_name': '{attributes[first_name][0]}',
149
    'last_name': '{attributes[last_name][0]}',
150
}
7 151

  
8
if 'DJANGO_CONFIG_FILE' in os.environ:
9
    logging.getLogger('hobo').debug('Loading setting file %r', os.environ['DJANGO_CONFIG_FILE'])
10
    execfile(os.environ['DJANGO_CONFIG_FILE'])
152
MELLON_SUPERUSER_MAPPING = {
153
    'roles': 'Admin::Hobo',
154
}
11 155

  
12
if 'DATABASES' not in globals():
13
    logging.getLogger('hobo').error('Unable to boot: You must define a DATABASES in your settings')
14
    raise ImproperlyConfigured('You must define a DATABASES variable in your settings')
156
MELLON_USERNAME_TEMPLATE = '{attributes[username][0]}'
15 157

  
158
local_settings_file = os.environ.get('HOBO_SETTINGS_FILE', 'local_settings.py')
159
if os.path.exists(local_settings_file):
160
    execfile(local_settings_file)
hobo/tenant_settings.py
1
from django.conf.global_settings import *
2
from hobo.default_settings import *
3
from django.core.exceptions import ImproperlyConfigured
4

  
5
import os
6
import logging
7

  
8
try:
9
    import entrouvert
10
except ImportError:
11
    raise ImproperlyConfigured('python-entrouvert MUST be installed for the multitenant mode to work')
12

  
13
DATABASES = {
14
    'default': {
15
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
16
        'NAME': 'portail_admin',
17
    },
18
}
19

  
20
TENANT_BASE = None
21
TENANT_TEMPLATE_DIRS = ( TENANT_BASE, )
22
TENANT_MODEL = 'multitenant.Tenant'
23

  
24
SOUTH_TESTS_MIGRATE = False
25
SOUTH_DATABASE_ADAPTERS = {
26
    'default': 'south.db.postgresql_psycopg2',
27
}
28

  
29
DEFAULT_FILE_STORAGE = 'entrouvert.djommon.multitenant.storage.TenantFileSystemStorage'
30

  
31
MIDDLEWARE_CLASSES = (
32
        'entrouvert.djommon.multitenant.middleware.TenantMiddleware',
33
        'entrouvert.djommon.multitenant.middleware.JSONSettingsMiddleware',
34
        'entrouvert.djommon.multitenant.middleware.PythonSettingsMiddleware',
35
) + MIDDLEWARE_CLASSES
36

  
37

  
38
TEMPLATE_LOADERS = (
39
    'entrouvert.djommon.multitenant.template_loader.FilesystemLoader',
40
    'django.template.loaders.filesystem.Loader',
41
    'django.template.loaders.app_directories.Loader',
42
)
43

  
44
PUBLIC_SCHEMA_URLCONF = 'hobo.manager_urls'
45

  
46
SHARED_APPS = (
47
    'django.contrib.auth',
48
    'django.contrib.contenttypes',
49
    'django.contrib.sessions',
50
    'django.contrib.messages',
51
    'django.contrib.staticfiles',
52
    'django.contrib.admin',
53
)
54

  
55
INSTALLED_APPS = INSTALLED_APPS + ('entrouvert.djommon.multitenant',)
56
TENANT_APPS = INSTALLED_APPS
57

  
58
if 'DJANGO_CONFIG_FILE' in os.environ:
59
    logging.getLogger('hobo').debug('Loading setting file %r', os.environ['DJANGO_CONFIG_FILE'])
60
    execfile(os.environ['DJANGO_CONFIG_FILE'])
61

  
62
if not TENANT_BASE:
63
    logging.getLogger('hobo').error('Unable to boot: You must define a TENANT_BASE in your settings')
64
    raise ImproperlyConfigured('You must define a TENANT_BASE in your settings')
65

  
66
if 'DATABASES' not in globals():
67
    logging.getLogger('hobo').error('Unable to boot: You must define a DATABASES in your settings')
68
    raise ImproperlyConfigured('You must define a DATABASES variable in your settings')
69

  
70
if DATABASES['default']['ENGINE'] != 'django.db.backends.postgresql_psycopg2':
71
    raise ImproperlyConfigured('MULTITENANT only work with django.db.backends.postgresql_psycopg2 Django db backend')
72
DATABASES['default']['ENGINE'] = 'tenant_schemas.postgresql_backend'
73

  
manage.py
3 3
import sys
4 4

  
5 5
if __name__ == "__main__":
6
    multitenant = False
7
    config_file = False
8

  
9
    argv = sys.argv[1:]
10
    for arg in list(argv):
11
        if arg.startswith('--'):
12
            if arg.startswith('--config='):
13
                config_file = arg.split('=')[1]
14
                argv.pop(0)
15
            elif arg == '--multitenant':
16
                multitenant = True
17
                argv.pop(0)
18
            else:
19
                print >>sys.stderr, 'ERR: Unsupported flag', arg
20
                sys.exit(1)
21
        else:
22
            break
23

  
24
    if config_file:
25
        os.environ['DJANGO_CONFIG_FILE'] = config_file
26

  
27
    if multitenant:
28
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hobo.tenant_settings")
29
    else:
30
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hobo.settings")
6
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hobo.settings")
31 7

  
32 8
    from django.core.management import execute_from_command_line
33 9

  
34
    execute_from_command_line(sys.argv[:1] + argv)
10
    execute_from_command_line(sys.argv)
35
-