blob: b28ddb2b0d5347a0ed75b3c34f9261002fa6530b [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001#
2# ex:ts=4:sw=4:sts=4:et
3# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
4#
5# BitBake Toaster Implementation
6#
7# Copyright (C) 2013 Intel Corporation
8#
9# This program is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License version 2 as
11# published by the Free Software Foundation.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License along
19# with this program; if not, write to the Free Software Foundation, Inc.,
20# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22# Django settings for Toaster project.
23
24import os, re
25
Patrick Williamsf1e5d692016-03-30 15:21:19 -050026# Temporary toggle for Image customisation
27CUSTOM_IMAGE = False
28if os.environ.get("CUSTOM_IMAGE", None) is not None:
29 CUSTOM_IMAGE = True
30
Patrick Williamsc124f4f2015-09-15 14:41:29 -050031DEBUG = True
32TEMPLATE_DEBUG = DEBUG
33
34# Set to True to see the SQL queries in console
35SQL_DEBUG = False
36if os.environ.get("TOASTER_SQLDEBUG", None) is not None:
37 SQL_DEBUG = True
38
39
40ADMINS = (
41 # ('Your Name', 'your_email@example.com'),
42)
43
44MANAGERS = ADMINS
45
46DATABASES = {
47 'default': {
48 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
49 'NAME': 'toaster.sqlite', # Or path to database file if using sqlite3.
50 'USER': '',
51 'PASSWORD': '',
52 'HOST': '127.0.0.1', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
53 'PORT': '3306', # Set to empty string for default.
54 }
55}
56
57# Needed when Using sqlite especially to add a longer timeout for waiting
58# for the database lock to be released
59# https://docs.djangoproject.com/en/1.6/ref/databases/#database-is-locked-errors
60if 'sqlite' in DATABASES['default']['ENGINE']:
61 DATABASES['default']['OPTIONS'] = { 'timeout': 20 }
62
63# Reinterpret database settings if we have DATABASE_URL environment variable defined
64
65if 'DATABASE_URL' in os.environ:
66 dburl = os.environ['DATABASE_URL']
67 if dburl.startswith('sqlite3://'):
68 result = re.match('sqlite3://(.*)', dburl)
69 if result is None:
70 raise Exception("ERROR: Could not read sqlite database url: %s" % dburl)
71 DATABASES['default'] = {
72 'ENGINE': 'django.db.backends.sqlite3',
73 'NAME': result.group(1),
74 'USER': '',
75 'PASSWORD': '',
76 'HOST': '',
77 'PORT': '',
78 }
79 elif dburl.startswith('mysql://'):
80 # URL must be in this form: mysql://user:pass@host:port/name
81 result = re.match(r"mysql://([^:]*):([^@]*)@([^:]*):(\d+)/([^/]*)", dburl)
82 if result is None:
83 raise Exception("ERROR: Could not read mysql database url: %s" % dburl)
84 DATABASES['default'] = {
85 'ENGINE': 'django.db.backends.mysql',
86 'NAME': result.group(5),
87 'USER': result.group(1),
88 'PASSWORD': result.group(2),
89 'HOST': result.group(3),
90 'PORT': result.group(4),
91 }
92 else:
93 raise Exception("FIXME: Please implement missing database url schema for url: %s" % dburl)
94
Patrick Williamsf1e5d692016-03-30 15:21:19 -050095BUILD_MODE = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -050096if 'TOASTER_MANAGED' in os.environ and os.environ['TOASTER_MANAGED'] == "1":
Patrick Williamsf1e5d692016-03-30 15:21:19 -050097 BUILD_MODE = True
Patrick Williamsc124f4f2015-09-15 14:41:29 -050098
99# Allows current database settings to be exported as a DATABASE_URL environment variable value
100
101def getDATABASE_URL():
102 d = DATABASES['default']
103 if d['ENGINE'] == 'django.db.backends.sqlite3':
104 if d['NAME'] == ':memory:':
105 return 'sqlite3://:memory:'
106 elif d['NAME'].startswith("/"):
107 return 'sqlite3://' + d['NAME']
108 return "sqlite3://" + os.path.join(os.getcwd(), d['NAME'])
109
110 elif d['ENGINE'] == 'django.db.backends.mysql':
111 return "mysql://" + d['USER'] + ":" + d['PASSWORD'] + "@" + d['HOST'] + ":" + d['PORT'] + "/" + d['NAME']
112
113 raise Exception("FIXME: Please implement missing database url schema for engine: %s" % d['ENGINE'])
114
115
116
117# Hosts/domain names that are valid for this site; required if DEBUG is False
118# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
119ALLOWED_HOSTS = []
120
121# Local time zone for this installation. Choices can be found here:
122# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
123# although not all choices may be available on all operating systems.
124# In a Windows environment this must be set to your system time zone.
125
126# Always use local computer's time zone, find
127import hashlib
128if 'TZ' in os.environ:
129 TIME_ZONE = os.environ['TZ']
130else:
131 # need to read the /etc/localtime file which is the libc standard
132 # and do a reverse-mapping to /usr/share/zoneinfo/;
133 # since the timezone may match any number of identical timezone definitions,
134
135 zonefilelist = {}
136 ZONEINFOPATH = '/usr/share/zoneinfo/'
137 for dirpath, dirnames, filenames in os.walk(ZONEINFOPATH):
138 for fn in filenames:
139 filepath = os.path.join(dirpath, fn)
140 zonename = filepath.lstrip(ZONEINFOPATH).strip()
141 try:
142 import pytz
143 from pytz.exceptions import UnknownTimeZoneError
144 pass
145 try:
146 if pytz.timezone(zonename) is not None:
147 zonefilelist[hashlib.md5(open(filepath).read()).hexdigest()] = zonename
148 except UnknownTimeZoneError, ValueError:
149 # we expect timezone failures here, just move over
150 pass
151 except ImportError:
152 zonefilelist[hashlib.md5(open(filepath).read()).hexdigest()] = zonename
153
154 TIME_ZONE = zonefilelist[hashlib.md5(open('/etc/localtime').read()).hexdigest()]
155
156# Language code for this installation. All choices can be found here:
157# http://www.i18nguy.com/unicode/language-identifiers.html
158LANGUAGE_CODE = 'en-us'
159
160SITE_ID = 1
161
162# If you set this to False, Django will make some optimizations so as not
163# to load the internationalization machinery.
164USE_I18N = True
165
166# If you set this to False, Django will not format dates, numbers and
167# calendars according to the current locale.
168USE_L10N = True
169
170# If you set this to False, Django will not use timezone-aware datetimes.
171USE_TZ = True
172
173# Absolute filesystem path to the directory that will hold user-uploaded files.
174# Example: "/var/www/example.com/media/"
175MEDIA_ROOT = ''
176
177# URL that handles the media served from MEDIA_ROOT. Make sure to use a
178# trailing slash.
179# Examples: "http://example.com/media/", "http://media.example.com/"
180MEDIA_URL = ''
181
182# Absolute path to the directory static files should be collected to.
183# Don't put anything in this directory yourself; store your static files
184# in apps' "static/" subdirectories and in STATICFILES_DIRS.
185# Example: "/var/www/example.com/static/"
186STATIC_ROOT = ''
187
188# URL prefix for static files.
189# Example: "http://example.com/static/", "http://static.example.com/"
190STATIC_URL = '/static/'
191
192# Additional locations of static files
193STATICFILES_DIRS = (
194 # Put strings here, like "/home/html/static" or "C:/www/django/static".
195 # Always use forward slashes, even on Windows.
196 # Don't forget to use absolute paths, not relative paths.
197)
198
199# List of finder classes that know how to find static files in
200# various locations.
201STATICFILES_FINDERS = (
202 'django.contrib.staticfiles.finders.FileSystemFinder',
203 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
204# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
205)
206
207# Make this unique, and don't share it with anybody.
208SECRET_KEY = 'NOT_SUITABLE_FOR_HOSTED_DEPLOYMENT'
209
210# List of callables that know how to import templates from various sources.
211TEMPLATE_LOADERS = (
212 'django.template.loaders.filesystem.Loader',
213 'django.template.loaders.app_directories.Loader',
214# 'django.template.loaders.eggs.Loader',
215)
216
217MIDDLEWARE_CLASSES = (
218 'django.middleware.common.CommonMiddleware',
219 'django.contrib.sessions.middleware.SessionMiddleware',
220 'django.middleware.csrf.CsrfViewMiddleware',
221 'django.contrib.auth.middleware.AuthenticationMiddleware',
222 'django.contrib.messages.middleware.MessageMiddleware',
223 # Uncomment the next line for simple clickjacking protection:
224 # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
225)
226
227CACHES = {
228 # 'default': {
229 # 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
230 # 'LOCATION': '127.0.0.1:11211',
231 # },
232 'default': {
233 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
234 'LOCATION': '/tmp/django-default-cache',
235 'TIMEOUT': 1,
236 }
237 }
238
239
240from os.path import dirname as DN
241SITE_ROOT=DN(DN(os.path.abspath(__file__)))
242
243import subprocess
244TOASTER_BRANCH = subprocess.Popen('git branch | grep "^* " | tr -d "* "', cwd = SITE_ROOT, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
245TOASTER_REVISION = subprocess.Popen('git rev-parse HEAD ', cwd = SITE_ROOT, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
246
247ROOT_URLCONF = 'toastermain.urls'
248
249# Python dotted path to the WSGI application used by Django's runserver.
250WSGI_APPLICATION = 'toastermain.wsgi.application'
251
252TEMPLATE_DIRS = (
253 # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
254 # Always use forward slashes, even on Windows.
255 # Don't forget to use absolute paths, not relative paths.
256)
257
258TEMPLATE_CONTEXT_PROCESSORS = ('django.contrib.auth.context_processors.auth',
259 'django.core.context_processors.debug',
260 'django.core.context_processors.i18n',
261 'django.core.context_processors.media',
262 'django.core.context_processors.static',
263 'django.core.context_processors.tz',
264 'django.contrib.messages.context_processors.messages',
265 "django.core.context_processors.request",
266 'toastergui.views.managedcontextprocessor',
267 )
268
269INSTALLED_APPS = (
270 'django.contrib.auth',
271 'django.contrib.contenttypes',
272 'django.contrib.messages',
273 'django.contrib.sessions',
274 'django.contrib.admin',
275 'django.contrib.staticfiles',
276
277 # Uncomment the next line to enable admin documentation:
278 # 'django.contrib.admindocs',
279 'django.contrib.humanize',
280 'bldcollector',
281 'toastermain',
282 'south',
283)
284
285
286INTERNAL_IPS = ['127.0.0.1', '192.168.2.28']
287
288# Load django-fresh is TOASTER_DEVEL is set, and the module is available
289FRESH_ENABLED = False
290if os.environ.get('TOASTER_DEVEL', None) is not None:
291 try:
292 import fresh
293 MIDDLEWARE_CLASSES = ("fresh.middleware.FreshMiddleware",) + MIDDLEWARE_CLASSES
294 INSTALLED_APPS = INSTALLED_APPS + ('fresh',)
295 FRESH_ENABLED = True
296 except:
297 pass
298
299DEBUG_PANEL_ENABLED = False
300if os.environ.get('TOASTER_DEVEL', None) is not None:
301 try:
302 import debug_toolbar, debug_panel
303 MIDDLEWARE_CLASSES = ('debug_panel.middleware.DebugPanelMiddleware',) + MIDDLEWARE_CLASSES
304 #MIDDLEWARE_CLASSES = MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware',)
305 INSTALLED_APPS = INSTALLED_APPS + ('debug_toolbar','debug_panel',)
306 DEBUG_PANEL_ENABLED = True
307
308 # this cache backend will be used by django-debug-panel
309 CACHES['debug-panel'] = {
310 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
311 'LOCATION': '/var/tmp/debug-panel-cache',
312 'TIMEOUT': 300,
313 'OPTIONS': {
314 'MAX_ENTRIES': 200
315 }
316 }
317
318 except:
319 pass
320
321
322SOUTH_TESTS_MIGRATE = False
323
324
325# We automatically detect and install applications here if
326# they have a 'models.py' or 'views.py' file
327import os
328currentdir = os.path.dirname(__file__)
329for t in os.walk(os.path.dirname(currentdir)):
330 modulename = os.path.basename(t[0])
331 #if we have a virtualenv skip it to avoid incorrect imports
332 if os.environ.has_key('VIRTUAL_ENV') and os.environ['VIRTUAL_ENV'] in t[0]:
333 continue
334
335 if ("views.py" in t[2] or "models.py" in t[2]) and not modulename in INSTALLED_APPS:
336 INSTALLED_APPS = INSTALLED_APPS + (modulename,)
337
338# A sample logging configuration. The only tangible logging
339# performed by this configuration is to send an email to
340# the site admins on every HTTP 500 error when DEBUG=False.
341# See http://docs.djangoproject.com/en/dev/topics/logging for
342# more details on how to customize your logging configuration.
343LOGGING = {
344 'version': 1,
345 'disable_existing_loggers': False,
346 'filters': {
347 'require_debug_false': {
348 '()': 'django.utils.log.RequireDebugFalse'
349 }
350 },
351 'formatters': {
352 'datetime': {
353 'format': '%(asctime)s %(levelname)s %(message)s'
354 }
355 },
356 'handlers': {
357 'mail_admins': {
358 'level': 'ERROR',
359 'filters': ['require_debug_false'],
360 'class': 'django.utils.log.AdminEmailHandler'
361 },
362 'console': {
363 'level': 'DEBUG',
364 'class': 'logging.StreamHandler',
365 'formatter': 'datetime',
366 }
367 },
368 'loggers': {
369 'toaster' : {
370 'handlers': ['console'],
371 'level': 'DEBUG',
372 },
373 'django.request': {
374 'handlers': ['console'],
375 'level': 'WARN',
376 'propagate': True,
377 },
378 }
379}
380
381if DEBUG and SQL_DEBUG:
382 LOGGING['loggers']['django.db.backends'] = {
383 'level': 'DEBUG',
384 'handlers': ['console'],
385 }
386
387
388# If we're using sqlite, we need to tweak the performance a bit
389from django.db.backends.signals import connection_created
390def activate_synchronous_off(sender, connection, **kwargs):
391 if connection.vendor == 'sqlite':
392 cursor = connection.cursor()
393 cursor.execute('PRAGMA synchronous = 0;')
394connection_created.connect(activate_synchronous_off)
395#
396
397
398class InvalidString(str):
399 def __mod__(self, other):
400 from django.template.base import TemplateSyntaxError
401 raise TemplateSyntaxError(
402 "Undefined variable or unknown value for: \"%s\"" % other)
403
404TEMPLATE_STRING_IF_INVALID = InvalidString("%s")
405
406import sys
407sys.path.append(
408 os.path.join(
409 os.path.join(
410 os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
411 "contrib"),
412 "django-aggregate-if-master")
413 )