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