settings.py 14 KB

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