PageRenderTime 36ms CodeModel.GetById 9ms RepoModel.GetById 1ms app.codeStats 0ms

/django/db/utils.py

https://bitbucket.org/taxilian/racecontrol5
Python | 170 lines | 142 code | 16 blank | 12 comment | 31 complexity | 639467ecb173ec94294c9cb1e631a59d MD5 | raw file
Possible License(s): BSD-3-Clause
  1. import inspect
  2. import os
  3. from django.conf import settings
  4. from django.core.exceptions import ImproperlyConfigured
  5. from django.utils.importlib import import_module
  6. DEFAULT_DB_ALIAS = 'default'
  7. # Define some exceptions that mirror the PEP249 interface.
  8. # We will rethrow any backend-specific errors using these
  9. # common wrappers
  10. class DatabaseError(Exception):
  11. pass
  12. class IntegrityError(DatabaseError):
  13. pass
  14. def load_backend(backend_name):
  15. try:
  16. module = import_module('.base', 'django.db.backends.%s' % backend_name)
  17. import warnings
  18. warnings.warn(
  19. "Short names for DATABASE_ENGINE are deprecated; prepend with 'django.db.backends.'",
  20. PendingDeprecationWarning
  21. )
  22. return module
  23. except ImportError, e:
  24. # Look for a fully qualified database backend name
  25. try:
  26. return import_module('.base', backend_name)
  27. except ImportError, e_user:
  28. # The database backend wasn't found. Display a helpful error message
  29. # listing all possible (built-in) database backends.
  30. backend_dir = os.path.join(os.path.dirname(__file__), 'backends')
  31. try:
  32. available_backends = [f for f in os.listdir(backend_dir)
  33. if os.path.isdir(os.path.join(backend_dir, f))
  34. and not f.startswith('.')]
  35. except EnvironmentError:
  36. available_backends = []
  37. available_backends.sort()
  38. if backend_name not in available_backends:
  39. error_msg = ("%r isn't an available database backend. \n" +
  40. "Try using django.db.backends.XXX, where XXX is one of:\n %s\n" +
  41. "Error was: %s") % \
  42. (backend_name, ", ".join(map(repr, available_backends)), e_user)
  43. raise ImproperlyConfigured(error_msg)
  44. else:
  45. raise # If there's some other error, this must be an error in Django itself.
  46. class ConnectionDoesNotExist(Exception):
  47. pass
  48. class ConnectionHandler(object):
  49. def __init__(self, databases):
  50. self.databases = databases
  51. self._connections = {}
  52. def ensure_defaults(self, alias):
  53. """
  54. Puts the defaults into the settings dictionary for a given connection
  55. where no settings is provided.
  56. """
  57. try:
  58. conn = self.databases[alias]
  59. except KeyError:
  60. raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias)
  61. conn.setdefault('ENGINE', 'django.db.backends.dummy')
  62. if conn['ENGINE'] == 'django.db.backends.' or not conn['ENGINE']:
  63. conn['ENGINE'] = 'django.db.backends.dummy'
  64. conn.setdefault('OPTIONS', {})
  65. conn.setdefault('TEST_CHARSET', None)
  66. conn.setdefault('TEST_COLLATION', None)
  67. conn.setdefault('TEST_NAME', None)
  68. conn.setdefault('TEST_MIRROR', None)
  69. conn.setdefault('TIME_ZONE', settings.TIME_ZONE)
  70. for setting in ('NAME', 'USER', 'PASSWORD', 'HOST', 'PORT'):
  71. conn.setdefault(setting, '')
  72. def __getitem__(self, alias):
  73. if alias in self._connections:
  74. return self._connections[alias]
  75. self.ensure_defaults(alias)
  76. db = self.databases[alias]
  77. backend = load_backend(db['ENGINE'])
  78. conn = backend.DatabaseWrapper(db, alias)
  79. self._connections[alias] = conn
  80. return conn
  81. def __iter__(self):
  82. return iter(self.databases)
  83. def all(self):
  84. return [self[alias] for alias in self]
  85. class ConnectionRouter(object):
  86. def __init__(self, routers):
  87. self.routers = []
  88. for r in routers:
  89. if isinstance(r, basestring):
  90. try:
  91. module_name, klass_name = r.rsplit('.', 1)
  92. module = import_module(module_name)
  93. except ImportError, e:
  94. raise ImproperlyConfigured('Error importing database router %s: "%s"' % (klass_name, e))
  95. try:
  96. router_class = getattr(module, klass_name)
  97. except AttributeError:
  98. raise ImproperlyConfigured('Module "%s" does not define a database router name "%s"' % (module, klass_name))
  99. else:
  100. router = router_class()
  101. else:
  102. router = r
  103. self.routers.append(router)
  104. def _router_func(action):
  105. def _route_db(self, model, **hints):
  106. chosen_db = None
  107. for router in self.routers:
  108. try:
  109. method = getattr(router, action)
  110. except AttributeError:
  111. # If the router doesn't have a method, skip to the next one.
  112. pass
  113. else:
  114. chosen_db = method(model, **hints)
  115. if chosen_db:
  116. return chosen_db
  117. try:
  118. return hints['instance']._state.db or DEFAULT_DB_ALIAS
  119. except KeyError:
  120. return DEFAULT_DB_ALIAS
  121. return _route_db
  122. db_for_read = _router_func('db_for_read')
  123. db_for_write = _router_func('db_for_write')
  124. def allow_relation(self, obj1, obj2, **hints):
  125. for router in self.routers:
  126. try:
  127. method = router.allow_relation
  128. except AttributeError:
  129. # If the router doesn't have a method, skip to the next one.
  130. pass
  131. else:
  132. allow = method(obj1, obj2, **hints)
  133. if allow is not None:
  134. return allow
  135. return obj1._state.db == obj2._state.db
  136. def allow_syncdb(self, db, model):
  137. for router in self.routers:
  138. try:
  139. method = router.allow_syncdb
  140. except AttributeError:
  141. # If the router doesn't have a method, skip to the next one.
  142. pass
  143. else:
  144. allow = method(db, model)
  145. if allow is not None:
  146. return allow
  147. return True