PageRenderTime 51ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/mezzanine/utils/conf.py

https://github.com/estherbester/mezzanine
Python | 179 lines | 171 code | 5 blank | 3 comment | 4 complexity | 07db80307063952200640ec2877ff594 MD5 | raw file
  1. import os
  2. import sys
  3. from django.template.loader import add_to_builtins
  4. from django import VERSION
  5. from mezzanine.utils.importing import path_for_import
  6. def set_dynamic_settings(s):
  7. """
  8. Called at the end of the project's settings module and is passed its
  9. globals dict for updating with some final tweaks for settings that
  10. generally aren't specified but can be given some better defaults based on
  11. other settings that have been specified. Broken out into its own
  12. function so that the code need not be replicated in the settings modules
  13. of other project-based apps that leverage Mezzanine's settings module.
  14. """
  15. s["TEMPLATE_DEBUG"] = s["DEBUG"]
  16. add_to_builtins("mezzanine.template.loader_tags")
  17. # Define some settings based on management command being run.
  18. management_command = sys.argv[1] if len(sys.argv) > 1 else ""
  19. # Some kind of testing is running via test or testserver
  20. s["TESTING"] = management_command.startswith("test")
  21. # Some kind of development server is running via runserver or runserver_plus
  22. s["DEV_SERVER"] = management_command.startswith("runserver")
  23. # Change INSTALLED_APPS to a list for easier manipulation.
  24. s["INSTALLED_APPS"] = list(s["INSTALLED_APPS"])
  25. # Setup for optional apps.
  26. if not s["TESTING"]:
  27. for app in s.get("OPTIONAL_APPS", []):
  28. if app not in s["INSTALLED_APPS"]:
  29. try:
  30. __import__(app)
  31. except ImportError:
  32. pass
  33. else:
  34. s["INSTALLED_APPS"].append(app)
  35. if "debug_toolbar" in s["INSTALLED_APPS"]:
  36. debug_mw = "debug_toolbar.middleware.DebugToolbarMiddleware"
  37. if debug_mw not in s["MIDDLEWARE_CLASSES"]:
  38. s["MIDDLEWARE_CLASSES"] = tuple(s["MIDDLEWARE_CLASSES"])
  39. s["MIDDLEWARE_CLASSES"] += (debug_mw,)
  40. if s.get("PACKAGE_NAME_FILEBROWSER") in s["INSTALLED_APPS"]:
  41. s["FILEBROWSER_URL_FILEBROWSER_MEDIA"] = "/filebrowser/media/"
  42. fb_path = path_for_import(s["PACKAGE_NAME_FILEBROWSER"])
  43. fb_media_path = os.path.join(fb_path, "media", "filebrowser")
  44. s["FILEBROWSER_PATH_FILEBROWSER_MEDIA"] = fb_media_path
  45. grappelli_name = s.get("PACKAGE_NAME_GRAPPELLI")
  46. s["GRAPPELLI_INSTALLED"] = grappelli_name in s["INSTALLED_APPS"]
  47. if s["GRAPPELLI_INSTALLED"]:
  48. # Ensure Grappelli is after Mezzanine in app order so that
  49. # admin templates are loaded in the correct order.
  50. s["INSTALLED_APPS"].remove(grappelli_name)
  51. s["INSTALLED_APPS"].append(grappelli_name)
  52. s["GRAPPELLI_ADMIN_HEADLINE"] = "Mezzanine"
  53. s["GRAPPELLI_ADMIN_TITLE"] = "Mezzanine"
  54. grappelli_path = path_for_import(s["PACKAGE_NAME_GRAPPELLI"])
  55. s["GRAPPELLI_MEDIA_PATH"] = os.path.join(grappelli_path, "media")
  56. # Adopted from django.core.management.commands.runserver
  57. # Easiest way so far to actually get all the media for Grappelli
  58. # working with the dev server is to hard-code the host:port to
  59. # ADMIN_MEDIA_PREFIX, so here we check for a custom host:port
  60. # before doing this.
  61. if len(sys.argv) >= 2 and sys.argv[1] == "runserver":
  62. addrport = ""
  63. if len(sys.argv) > 2:
  64. addrport = sys.argv[2]
  65. if not addrport:
  66. addr, port = "", "8000"
  67. else:
  68. try:
  69. addr, port = addrport.split(":")
  70. except ValueError:
  71. addr, port = "", addrport
  72. if not addr:
  73. addr = "127.0.0.1"
  74. parts = (addr, port, s["ADMIN_MEDIA_PREFIX"])
  75. s["ADMIN_MEDIA_PREFIX"] = "http://%s:%s%s" % parts
  76. # Ensure admin is last in the app order so that admin templates
  77. # are loaded in the correct order.
  78. if "django.contrib.admin" in s["INSTALLED_APPS"]:
  79. s["INSTALLED_APPS"].remove("django.contrib.admin")
  80. s["INSTALLED_APPS"].append("django.contrib.admin")
  81. # Add missing apps if existing apps depend on them.
  82. if ("mezzanine.blog" in s["INSTALLED_APPS"] and
  83. "mezzanine.generic" not in s["INSTALLED_APPS"]):
  84. s["INSTALLED_APPS"].append("mezzanine.generic")
  85. if "mezzanine.generic" in s["INSTALLED_APPS"]:
  86. s["COMMENTS_APP"] = "mezzanine.generic"
  87. if "django.contrib.comments" not in s["INSTALLED_APPS"]:
  88. s["INSTALLED_APPS"].append("django.contrib.comments")
  89. # Change INSTALLED_APPS back to a tuple.
  90. s["INSTALLED_APPS"] = tuple(s["INSTALLED_APPS"])
  91. # Caching.
  92. if not (s.get("CACHE_BACKEND") or s.get("CACHES")):
  93. s["MIDDLEWARE_CLASSES"] = [mw for mw in s["MIDDLEWARE_CLASSES"] if not
  94. mw.endswith("UpdateCacheMiddleware") or
  95. mw.endswith("FetchFromCacheMiddleware")]
  96. # Some settings tweaks for different DB engines.
  97. backend_path = "django.db.backends."
  98. backend_shortnames = (
  99. "postgresql_psycopg2",
  100. "postgresql",
  101. "mysql",
  102. "sqlite3",
  103. "oracle",
  104. )
  105. for (key, db) in s["DATABASES"].items():
  106. if db["ENGINE"] in backend_shortnames:
  107. s["DATABASES"][key]["ENGINE"] = backend_path + db["ENGINE"]
  108. shortname = db["ENGINE"].split(".")[-1]
  109. if shortname == "sqlite3" and os.sep not in db["NAME"]:
  110. # If the Sqlite DB name doesn't contain a path, assume it's
  111. # in the project directory and add the path to it.
  112. s["DATABASES"][key]["NAME"] = os.path.join(
  113. s.get("PROJECT_ROOT", ""), db["NAME"])
  114. elif shortname == "mysql":
  115. # Required MySQL collation for tests.
  116. s["DATABASES"][key]["TEST_COLLATION"] = "utf8_general_ci"
  117. elif shortname.startswith("postgresql") and not s.get("TIME_ZONE", 1):
  118. # Specifying a blank time zone to fall back to the system's
  119. # time zone will break table creation in Postgres so remove it.
  120. del s["TIME_ZONE"]
  121. # If a theme is defined then add its template path to the template dirs.
  122. theme = s.get("THEME")
  123. if theme:
  124. theme_templates = os.path.join(path_for_import(theme), "templates")
  125. s["TEMPLATE_DIRS"] = (theme_templates,) + tuple(s["TEMPLATE_DIRS"])
  126. # Remaining code is for Django 1.1 support.
  127. if VERSION >= (1, 2, 0):
  128. return
  129. # Add the dummy csrf_token template tag to builtins and remove
  130. # Django's CsrfViewMiddleware.
  131. add_to_builtins("mezzanine.core.templatetags.dummy_csrf")
  132. s["MIDDLEWARE_CLASSES"] = [mw for mw in s["MIDDLEWARE_CLASSES"] if
  133. mw != "django.middleware.csrf.CsrfViewMiddleware"]
  134. # Use the single DB settings.
  135. old_db_settings_mapping = {
  136. "ENGINE": "DATABASE_ENGINE",
  137. "HOST": "DATABASE_HOST",
  138. "NAME": "DATABASE_NAME",
  139. "OPTIONS": "DATABASE_OPTIONS",
  140. "PASSWORD": "DATABASE_PASSWORD",
  141. "PORT": "DATABASE_PORT",
  142. "USER": "DATABASE_USER",
  143. "TEST_CHARSET": "TEST_DATABASE_CHARSET",
  144. "TEST_COLLATION": "TEST_DATABASE_COLLATION",
  145. "TEST_NAME": "TEST_DATABASE_NAME",
  146. }
  147. for (new_name, old_name) in old_db_settings_mapping.items():
  148. value = s["DATABASES"]["default"].get(new_name)
  149. if value is not None:
  150. if new_name == "ENGINE" and value.startswith(backend_path):
  151. value = value.replace(backend_path, "", 1)
  152. s[old_name] = value
  153. # Revert to some old names.
  154. processors = list(s["TEMPLATE_CONTEXT_PROCESSORS"])
  155. for (i, processor) in enumerate(processors):
  156. if processor == "django.contrib.auth.context_processors.auth":
  157. processors[i] = "django.core.context_processors.auth"
  158. s["TEMPLATE_CONTEXT_PROCESSORS"] = processors
  159. loaders = list(s["TEMPLATE_LOADERS"])
  160. for (i, loader) in enumerate(loaders):
  161. if loader.startswith("django.") and loader.endswith(".Loader"):
  162. loaders[i] = loader.replace(".Loader", ".load_template_source", 1)
  163. s["TEMPLATE_LOADERS"] = loaders