forked from janatalab/pyensemble
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsettings.py
More file actions
365 lines (294 loc) · 10.8 KB
/
settings.py
File metadata and controls
365 lines (294 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
"""
Django settings for pyensemble project.
Generated by 'django-admin startproject' using Django 2.2.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
from pathlib import Path
import json
from configparser import ConfigParser
import pdb
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
"""
Specify the label for this particular installation of PyEnsemble.
This is effectively the namespace that distinguishes multiple PyEnsemble instances on a single server from each other.
"""
INSTANCE_LABEL = 'pyensemble'
"""
Specify the path to password and settings files.
The local directory (pyensemble.settings.local) is excluded from git commits and thus a reasonable space to store secrets and credentials associated with this instance.
"""
PASS_DIR = os.path.join(BASE_DIR, 'pyensemble/settings/local')
"""
An example of an alternative location at which to store credentials. Might be useful in production server contexts.
"""
# PASS_DIR = os.path.join('/var/www/private', INSTANCE_LABEL)
# Specify the file that contains our various custom settings and secrets
SITE_CONFIG_FILE = os.path.join(PASS_DIR, 'pyensemble_params.ini')
# For development purposes, utilize pyensemble.settings.local
# PASS_DIR = os.path.join(BASE_DIR, 'pyensemble/settings/local')
# Specify the directory where experiments will be located
EXPERIMENT_DIR = os.path.join(BASE_DIR,'pyensemble/experiments')
# Open our configuration file
config = ConfigParser()
config.read(SITE_CONFIG_FILE)
# Get our Django secret
SECRET_KEY = config['django']['secret']
# Specify the list of allowed hosts. Note, these must be specified as a list in the configuration file, with double quotes surrounding each hostname
ALLOWED_HOSTS = json.loads(config['django']['allowed_hosts'])
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'encrypted_model_fields',
'django_recaptcha',
'crispy_forms',
'crispy_bootstrap4',
'storages',
'rest_framework',
'pyensemble',
'pyensemble.group',
'pyensemble.integrations',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'pyensemble.middleware.TimezoneMiddleware',
]
ROOT_URLCONF = 'pyensemble.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': False, # we actually explicitly turn this on in loaders option
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
],
'loaders': [
('django.template.loaders.app_directories.Loader'),
('pyensemble.experiments.loaders.Loader',),
]
},
},
]
CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap4"
CRISPY_TEMPLATE_PACK = 'bootstrap4'
WSGI_APPLICATION = 'pyensemble.wsgi.application'
# Database
DATABASES = {
'default': {
'ENGINE': config['django-db'].get('engine', 'django.db.backends.mysql'),
'HOST': config['django-db']['host'],
'NAME': config['django-db']['name'],
'USER': config['django-db']['user'],
'PASSWORD': config['django-db']['passwd'],
'PORT': '3306', # 3306 is the default mysql port
'OPTIONS': {}
}
}
# Add ssl info if we are dealing with a MySQL database
ssl_backends = ['django.db.backends.mysql']
if DATABASES['default']['ENGINE'] in ssl_backends:
if config['django-db'].get('ssl_certpath', None):
ssl_certpath = config['django-db']['ssl_certpath']
else:
ssl_certpath = PASS_DIR
DATABASES['default']['OPTIONS']['ssl'] = {
'ca': os.path.join(ssl_certpath, config['django-db']['ssl_certname']),
}
# Set other mysql specific options
if DATABASES['default']['ENGINE'] == 'django.db.backends.mysql':
DATABASES['default']['OPTIONS']['init_command'] = "SET sql_mode='STRICT_TRANS_TABLES'"
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
# Get the encryption key for the Subject table fields
FIELD_ENCRYPTION_KEY = config['django']['field_encryption_key']
# Specify cache engine
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
'LOCATION': ['127.0.0.1:11211'],
'TIMEOUT': 60*60*6,
'NAME': '',
},
}
# Specify that we are using the cache for maintaining session info
SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
USE_TZ = True
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
USE_AWS_STORAGE = False
STORAGES = {
"default": {
"BACKEND": "django.core.files.storage.FileSystemStorage",
},
"staticfiles": {
"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage",
},
}
STATIC_ROOT = os.path.join('/var/www/html/static/', INSTANCE_LABEL)
STATIC_URL = f"/static/{INSTANCE_LABEL}/"
MEDIA_ROOT = config['django']['media_root']
MEDIA_URL = config['django']['media_url']
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "thirdparty/"),
]
# SITE stuff
SITE_ID = 1
PORT = '' # use '' for default http(s) ports
# Login and logout stuff
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = '/'
# Various things pertaining to sessions
SESSION_DURATION=60*60*24 # default session duration
# Email related stuff
if 'email' in config.sections():
email_params = config['email']
EMAIL_HOST = email_params['host']
EMAIL_HOST_USER = email_params['host_user']
EMAIL_HOST_PASSWORD = email_params['host_password']
EMAIL_PORT = email_params['port']
EMAIL_USE_TLS = email_params['use_tls']
DEFAULT_FROM_EMAIL = email_params['default_from_email']
SERVER_EMAIL = EMAIL_HOST_USER
# Logging
LOG_DIR = config['django']['logdir']
# Make sure the log directory exists
Path(LOG_DIR).mkdir(parents=True, exist_ok=True)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'timestamped': {
'format': '%(levelname)s: %(asctime)s %(module)s %(message)s',
},
'experiment': {
'format': '%(levelname)s: %(asctime)s %(pathname)s (%(funcName)s): %(message)s',
}
},
'handlers': {
'experiment-debug-file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': os.path.join(LOG_DIR,'experiment-debug.txt'),
'formatter': 'experiment',
},
'debug-file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': os.path.join(LOG_DIR,'django-debug.txt'),
'formatter': 'timestamped',
},
'error-file': {
'level': 'ERROR',
'class': 'logging.FileHandler',
'filename': os.path.join(LOG_DIR,'django-error.txt'),
'formatter': 'timestamped',
},
'template-file': {
'level': 'ERROR',
'class': 'logging.FileHandler',
'filename': os.path.join(LOG_DIR,'django-template.txt'),
'formatter': 'timestamped',
}
},
'loggers': {
'django.request': {
'handlers': ['debug-file','error-file'],
'propagate': True,
},
'django.template': {
'handlers': ['template-file'],
'level': 'ERROR',
'propagate': True,
},
'pyensemble': {
'handlers': ['debug-file', 'error-file'],
'level': 'DEBUG',
},
'pyensemble.experiments': {
'handlers': ['experiment-debug-file'],
'level': 'DEBUG',
'propagate': False,
},
},
}
#
# Integrations
#
# Google
if 'google' in config.sections():
NOCAPTCHA = True
RECAPTCHA_PUBLIC_KEY = config['google']['recaptcha_key']
RECAPTCHA_PRIVATE_KEY = config['google']['recaptcha_secret']
# AWS
if 'aws' in config.sections():
aws_params = config['aws']
USE_AWS_STORAGE = True
AWS_ACCESS_KEY_ID = aws_params['s3_client_id']
AWS_SECRET_ACCESS_KEY = aws_params['s3_client_secret']
AWS_STORAGE_BUCKET_NAME = aws_params['s3_static_bucket_name']
AWS_S3_CUSTOM_STATIC_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {}
AWS_LOCATION = INSTANCE_LABEL
STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_STATIC_DOMAIN, AWS_LOCATION)
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STORAGES['staticfiles'] = {'BACKEND': "storages.backends.s3.S3Storage"}
AWS_MEDIA_STORAGE_BUCKET_NAME = aws_params['s3_media_bucket_name']
AWS_S3_CUSTOM_MEDIA_DOMAIN = '%s.s3.amazonaws.com' % AWS_MEDIA_STORAGE_BUCKET_NAME
MEDIA_ROOT = ""
MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_MEDIA_DOMAIN, AWS_LOCATION)
AWS_DATA_STORAGE_BUCKET_NAME = aws_params['s3_data_bucket_name']
# Spotify
if 'spotify' in config.sections():
SPOTIFY_CLIENT_ID = config['spotify']['client_id']
SPOTIFY_CLIENT_SECRET = config['spotify']['client_secret']
# Prolific
if config.has_section('prolific'):
PROLIFIC_API = config['prolific']['api_endpoint']
PROLIFIC_TOKEN = config['prolific']['api_token']
PROLIFIC_WORKSPACE_ID = config['prolific']['workspace_id']
PROLIFIC_TESTER_IDS = json.loads(config['prolific']['tester_ids'])