Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.py 9.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import pkgutil
  2. from importlib import import_module
  3. from django.conf import settings
  4. from django.core.exceptions import ImproperlyConfigured
  5. # For backwards compatibility with Django < 3.2
  6. from django.utils.connection import ConnectionDoesNotExist # NOQA: F401
  7. from django.utils.connection import BaseConnectionHandler
  8. from django.utils.functional import cached_property
  9. from django.utils.module_loading import import_string
  10. DEFAULT_DB_ALIAS = "default"
  11. DJANGO_VERSION_PICKLE_KEY = "_django_version"
  12. class Error(Exception):
  13. pass
  14. class InterfaceError(Error):
  15. pass
  16. class DatabaseError(Error):
  17. pass
  18. class DataError(DatabaseError):
  19. pass
  20. class OperationalError(DatabaseError):
  21. pass
  22. class IntegrityError(DatabaseError):
  23. pass
  24. class InternalError(DatabaseError):
  25. pass
  26. class ProgrammingError(DatabaseError):
  27. pass
  28. class NotSupportedError(DatabaseError):
  29. pass
  30. class DatabaseErrorWrapper:
  31. """
  32. Context manager and decorator that reraises backend-specific database
  33. exceptions using Django's common wrappers.
  34. """
  35. def __init__(self, wrapper):
  36. """
  37. wrapper is a database wrapper.
  38. It must have a Database attribute defining PEP-249 exceptions.
  39. """
  40. self.wrapper = wrapper
  41. def __enter__(self):
  42. pass
  43. def __exit__(self, exc_type, exc_value, traceback):
  44. if exc_type is None:
  45. return
  46. for dj_exc_type in (
  47. DataError,
  48. OperationalError,
  49. IntegrityError,
  50. InternalError,
  51. ProgrammingError,
  52. NotSupportedError,
  53. DatabaseError,
  54. InterfaceError,
  55. Error,
  56. ):
  57. db_exc_type = getattr(self.wrapper.Database, dj_exc_type.__name__)
  58. if issubclass(exc_type, db_exc_type):
  59. dj_exc_value = dj_exc_type(*exc_value.args)
  60. # Only set the 'errors_occurred' flag for errors that may make
  61. # the connection unusable.
  62. if dj_exc_type not in (DataError, IntegrityError):
  63. self.wrapper.errors_occurred = True
  64. raise dj_exc_value.with_traceback(traceback) from exc_value
  65. def __call__(self, func):
  66. # Note that we are intentionally not using @wraps here for performance
  67. # reasons. Refs #21109.
  68. def inner(*args, **kwargs):
  69. with self:
  70. return func(*args, **kwargs)
  71. return inner
  72. def load_backend(backend_name):
  73. """
  74. Return a database backend's "base" module given a fully qualified database
  75. backend name, or raise an error if it doesn't exist.
  76. """
  77. # This backend was renamed in Django 1.9.
  78. if backend_name == "django.db.backends.postgresql_psycopg2":
  79. backend_name = "django.db.backends.postgresql"
  80. try:
  81. return import_module("%s.base" % backend_name)
  82. except ImportError as e_user:
  83. # The database backend wasn't found. Display a helpful error message
  84. # listing all built-in database backends.
  85. import django.db.backends
  86. builtin_backends = [
  87. name
  88. for _, name, ispkg in pkgutil.iter_modules(django.db.backends.__path__)
  89. if ispkg and name not in {"base", "dummy"}
  90. ]
  91. if backend_name not in ["django.db.backends.%s" % b for b in builtin_backends]:
  92. backend_reprs = map(repr, sorted(builtin_backends))
  93. raise ImproperlyConfigured(
  94. "%r isn't an available database backend or couldn't be "
  95. "imported. Check the above exception. To use one of the "
  96. "built-in backends, use 'django.db.backends.XXX', where XXX "
  97. "is one of:\n"
  98. " %s" % (backend_name, ", ".join(backend_reprs))
  99. ) from e_user
  100. else:
  101. # If there's some other error, this must be an error in Django
  102. raise
  103. class ConnectionHandler(BaseConnectionHandler):
  104. settings_name = "DATABASES"
  105. # Connections needs to still be an actual thread local, as it's truly
  106. # thread-critical. Database backends should use @async_unsafe to protect
  107. # their code from async contexts, but this will give those contexts
  108. # separate connections in case it's needed as well. There's no cleanup
  109. # after async contexts, though, so we don't allow that if we can help it.
  110. thread_critical = True
  111. def configure_settings(self, databases):
  112. databases = super().configure_settings(databases)
  113. if databases == {}:
  114. databases[DEFAULT_DB_ALIAS] = {"ENGINE": "django.db.backends.dummy"}
  115. elif DEFAULT_DB_ALIAS not in databases:
  116. raise ImproperlyConfigured(
  117. f"You must define a '{DEFAULT_DB_ALIAS}' database."
  118. )
  119. elif databases[DEFAULT_DB_ALIAS] == {}:
  120. databases[DEFAULT_DB_ALIAS]["ENGINE"] = "django.db.backends.dummy"
  121. # Configure default settings.
  122. for conn in databases.values():
  123. conn.setdefault("ATOMIC_REQUESTS", False)
  124. conn.setdefault("AUTOCOMMIT", True)
  125. conn.setdefault("ENGINE", "django.db.backends.dummy")
  126. if conn["ENGINE"] == "django.db.backends." or not conn["ENGINE"]:
  127. conn["ENGINE"] = "django.db.backends.dummy"
  128. conn.setdefault("CONN_MAX_AGE", 0)
  129. conn.setdefault("CONN_HEALTH_CHECKS", False)
  130. conn.setdefault("OPTIONS", {})
  131. conn.setdefault("TIME_ZONE", None)
  132. for setting in ["NAME", "USER", "PASSWORD", "HOST", "PORT"]:
  133. conn.setdefault(setting, "")
  134. test_settings = conn.setdefault("TEST", {})
  135. default_test_settings = [
  136. ("CHARSET", None),
  137. ("COLLATION", None),
  138. ("MIGRATE", True),
  139. ("MIRROR", None),
  140. ("NAME", None),
  141. ]
  142. for key, value in default_test_settings:
  143. test_settings.setdefault(key, value)
  144. return databases
  145. @property
  146. def databases(self):
  147. # Maintained for backward compatibility as some 3rd party packages have
  148. # made use of this private API in the past. It is no longer used within
  149. # Django itself.
  150. return self.settings
  151. def create_connection(self, alias):
  152. db = self.settings[alias]
  153. backend = load_backend(db["ENGINE"])
  154. return backend.DatabaseWrapper(db, alias)
  155. class ConnectionRouter:
  156. def __init__(self, routers=None):
  157. """
  158. If routers is not specified, default to settings.DATABASE_ROUTERS.
  159. """
  160. self._routers = routers
  161. @cached_property
  162. def routers(self):
  163. if self._routers is None:
  164. self._routers = settings.DATABASE_ROUTERS
  165. routers = []
  166. for r in self._routers:
  167. if isinstance(r, str):
  168. router = import_string(r)()
  169. else:
  170. router = r
  171. routers.append(router)
  172. return routers
  173. def _router_func(action):
  174. def _route_db(self, model, **hints):
  175. chosen_db = None
  176. for router in self.routers:
  177. try:
  178. method = getattr(router, action)
  179. except AttributeError:
  180. # If the router doesn't have a method, skip to the next one.
  181. pass
  182. else:
  183. chosen_db = method(model, **hints)
  184. if chosen_db:
  185. return chosen_db
  186. instance = hints.get("instance")
  187. if instance is not None and instance._state.db:
  188. return instance._state.db
  189. return DEFAULT_DB_ALIAS
  190. return _route_db
  191. db_for_read = _router_func("db_for_read")
  192. db_for_write = _router_func("db_for_write")
  193. def allow_relation(self, obj1, obj2, **hints):
  194. for router in self.routers:
  195. try:
  196. method = router.allow_relation
  197. except AttributeError:
  198. # If the router doesn't have a method, skip to the next one.
  199. pass
  200. else:
  201. allow = method(obj1, obj2, **hints)
  202. if allow is not None:
  203. return allow
  204. return obj1._state.db == obj2._state.db
  205. def allow_migrate(self, db, app_label, **hints):
  206. for router in self.routers:
  207. try:
  208. method = router.allow_migrate
  209. except AttributeError:
  210. # If the router doesn't have a method, skip to the next one.
  211. continue
  212. allow = method(db, app_label, **hints)
  213. if allow is not None:
  214. return allow
  215. return True
  216. def allow_migrate_model(self, db, model):
  217. return self.allow_migrate(
  218. db,
  219. model._meta.app_label,
  220. model_name=model._meta.model_name,
  221. model=model,
  222. )
  223. def get_migratable_models(self, app_config, db, include_auto_created=False):
  224. """Return app models allowed to be migrated on provided db."""
  225. models = app_config.get_models(include_auto_created=include_auto_created)
  226. return [model for model in models if self.allow_migrate_model(db, model)]