PageRenderTime 81ms CodeModel.GetById 38ms RepoModel.GetById 0ms app.codeStats 0ms

/examples/itemisApp.gae/src/djangoappengine/boot.py

https://github.com/aruder77/applause
Python | 177 lines | 167 code | 4 blank | 6 comment | 7 complexity | 6b3f77ebe554ae12de0625b161d62a8c MD5 | raw file
  1. import logging
  2. import os
  3. import sys
  4. PROJECT_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
  5. # Overrides for os.environ
  6. env_ext = {'DJANGO_SETTINGS_MODULE': 'settings'}
  7. def setup_env():
  8. """Configures app engine environment for command-line apps."""
  9. # Try to import the appengine code from the system path.
  10. try:
  11. from google.appengine.api import apiproxy_stub_map
  12. except ImportError:
  13. for k in [k for k in sys.modules if k.startswith('google')]:
  14. del sys.modules[k]
  15. # Not on the system path. Build a list of alternative paths where it
  16. # may be. First look within the project for a local copy, then look for
  17. # where the Mac OS SDK installs it.
  18. paths = [os.path.join(PROJECT_DIR, '.google_appengine'),
  19. os.environ.get('APP_ENGINE_SDK'),
  20. '/usr/local/google_appengine',
  21. '/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine']
  22. for path in os.environ.get('PATH', '').split(os.pathsep):
  23. path = path.rstrip(os.sep)
  24. if path.endswith('google_appengine'):
  25. paths.append(path)
  26. if os.name in ('nt', 'dos'):
  27. path = r'%(PROGRAMFILES)s\Google\google_appengine' % os.environ
  28. paths.append(path)
  29. # Loop through all possible paths and look for the SDK dir.
  30. sdk_path = None
  31. for path in paths:
  32. if not path:
  33. continue
  34. path = os.path.realpath(path)
  35. if os.path.exists(path):
  36. sdk_path = path
  37. break
  38. if sdk_path is None:
  39. # The SDK could not be found in any known location.
  40. sys.stderr.write('The Google App Engine SDK could not be found!\n'
  41. "Make sure it's accessible via your PATH "
  42. "environment and called google_appengine.")
  43. sys.exit(1)
  44. # Add the SDK and the libraries within it to the system path.
  45. extra_paths = [sdk_path]
  46. lib = os.path.join(sdk_path, 'lib')
  47. # Automatically add all packages in the SDK's lib folder:
  48. for dir in os.listdir(lib):
  49. path = os.path.join(lib, dir)
  50. # Package can be under 'lib/<pkg>/<pkg>/' or 'lib/<pkg>/lib/<pkg>/'
  51. detect = (os.path.join(path, dir), os.path.join(path, 'lib', dir))
  52. for path in detect:
  53. if os.path.isdir(path) and not dir == 'django':
  54. extra_paths.append(os.path.dirname(path))
  55. break
  56. sys.path = extra_paths + sys.path
  57. from google.appengine.api import apiproxy_stub_map
  58. setup_project()
  59. from .utils import have_appserver
  60. if have_appserver:
  61. # App Engine's threading.local is broken
  62. setup_threading()
  63. setup_logging()
  64. if not have_appserver:
  65. # Patch Django to support loading management commands from zip files
  66. from django.core import management
  67. management.find_commands = find_commands
  68. def find_commands(management_dir):
  69. """
  70. Given a path to a management directory, returns a list of all the command
  71. names that are available.
  72. This version works for django deployments which are file based or
  73. contained in a ZIP (in sys.path).
  74. Returns an empty list if no commands are defined.
  75. """
  76. import pkgutil
  77. return [modname for importer, modname, ispkg in pkgutil.iter_modules(
  78. [os.path.join(management_dir, 'commands')]) if not ispkg]
  79. def setup_threading():
  80. # XXX: GAE's threading.local doesn't work correctly with subclassing
  81. try:
  82. from django.utils._threading_local import local
  83. import threading
  84. threading.local = local
  85. except ImportError:
  86. pass
  87. def setup_logging():
  88. # Fix Python 2.6 logging module
  89. logging.logMultiprocessing = 0
  90. # Enable logging
  91. level = logging.DEBUG
  92. from .utils import have_appserver
  93. if have_appserver:
  94. # We can't import settings at this point when running a normal
  95. # manage.py command because this module gets imported from settings.py
  96. from django.conf import settings
  97. if not settings.DEBUG:
  98. level = logging.INFO
  99. logging.getLogger().setLevel(level)
  100. def setup_project():
  101. from .utils import have_appserver, on_production_server
  102. if have_appserver:
  103. # This fixes a pwd import bug for os.path.expanduser()
  104. env_ext['HOME'] = PROJECT_DIR
  105. # The dev_appserver creates a sandbox which restricts access to certain
  106. # modules and builtins in order to emulate the production environment.
  107. # Here we get the subprocess module back into the dev_appserver sandbox.
  108. # This module is just too important for development.
  109. # Also we add the compiler/parser module back and enable https connections
  110. # (seem to be broken on Windows because the _ssl module is disallowed).
  111. if not have_appserver:
  112. from google.appengine.tools import dev_appserver
  113. try:
  114. # Backup os.environ. It gets overwritten by the dev_appserver,
  115. # but it's needed by the subprocess module.
  116. env = dev_appserver.DEFAULT_ENV
  117. dev_appserver.DEFAULT_ENV = os.environ.copy()
  118. dev_appserver.DEFAULT_ENV.update(env)
  119. # Backup the buffer() builtin. The subprocess in Python 2.5 on
  120. # Linux and OS X uses needs it, but the dev_appserver removes it.
  121. dev_appserver.buffer = buffer
  122. except AttributeError:
  123. logging.warn('Could not patch the default environment. '
  124. 'The subprocess module will not work correctly.')
  125. try:
  126. # Allow importing compiler/parser and _ssl modules (for https)
  127. dev_appserver.HardenedModulesHook._WHITE_LIST_C_MODULES.extend(
  128. ('parser', '_ssl'))
  129. except AttributeError:
  130. logging.warn('Could not patch modules whitelist. '
  131. 'The compiler and parser modules will not work and '
  132. 'SSL support is disabled.')
  133. elif not on_production_server:
  134. try:
  135. # Restore the real subprocess module
  136. from google.appengine.api.mail_stub import subprocess
  137. sys.modules['subprocess'] = subprocess
  138. # Re-inject the buffer() builtin into the subprocess module
  139. from google.appengine.tools import dev_appserver
  140. subprocess.buffer = dev_appserver.buffer
  141. except Exception, e:
  142. logging.warn('Could not add the subprocess module to the sandbox: %s' % e)
  143. os.environ.update(env_ext)
  144. extra_paths = [PROJECT_DIR, os.path.join(os.path.dirname(__file__), 'lib')]
  145. zip_packages_dir = os.path.join(PROJECT_DIR, 'zip-packages')
  146. # We support zipped packages in the common and project folders.
  147. if os.path.isdir(zip_packages_dir):
  148. for zip_package in os.listdir(zip_packages_dir):
  149. extra_paths.append(os.path.join(zip_packages_dir, zip_package))
  150. # App Engine causes main.py to be reloaded if an exception gets raised
  151. # on the first request of a main.py instance, so don't call setup_project()
  152. # multiple times. We ensure this indirectly by checking if we've already
  153. # modified sys.path, already.
  154. if len(sys.path) < len(extra_paths) or \
  155. sys.path[:len(extra_paths)] != extra_paths:
  156. for path in extra_paths:
  157. while path in sys.path:
  158. sys.path.remove(path)
  159. sys.path = extra_paths + sys.path