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.

__init__.py 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from django.core import signals
  2. from django.db.utils import (
  3. DEFAULT_DB_ALIAS, DJANGO_VERSION_PICKLE_KEY, ConnectionHandler,
  4. ConnectionRouter, DatabaseError, DataError, Error, IntegrityError,
  5. InterfaceError, InternalError, NotSupportedError, OperationalError,
  6. ProgrammingError,
  7. )
  8. __all__ = [
  9. 'connection', 'connections', 'router', 'DatabaseError', 'IntegrityError',
  10. 'InternalError', 'ProgrammingError', 'DataError', 'NotSupportedError',
  11. 'Error', 'InterfaceError', 'OperationalError', 'DEFAULT_DB_ALIAS',
  12. 'DJANGO_VERSION_PICKLE_KEY',
  13. ]
  14. connections = ConnectionHandler()
  15. router = ConnectionRouter()
  16. class DefaultConnectionProxy:
  17. """
  18. Proxy for accessing the default DatabaseWrapper object's attributes. If you
  19. need to access the DatabaseWrapper object itself, use
  20. connections[DEFAULT_DB_ALIAS] instead.
  21. """
  22. def __getattr__(self, item):
  23. return getattr(connections[DEFAULT_DB_ALIAS], item)
  24. def __setattr__(self, name, value):
  25. return setattr(connections[DEFAULT_DB_ALIAS], name, value)
  26. def __delattr__(self, name):
  27. return delattr(connections[DEFAULT_DB_ALIAS], name)
  28. def __eq__(self, other):
  29. return connections[DEFAULT_DB_ALIAS] == other
  30. # For backwards compatibility. Prefer connections['default'] instead.
  31. connection = DefaultConnectionProxy()
  32. # Register an event to reset saved queries when a Django request is started.
  33. def reset_queries(**kwargs):
  34. for conn in connections.all():
  35. conn.queries_log.clear()
  36. signals.request_started.connect(reset_queries)
  37. # Register an event to reset transaction state and close connections past
  38. # their lifetime.
  39. def close_old_connections(**kwargs):
  40. for conn in connections.all():
  41. conn.close_if_unusable_or_obsolete()
  42. signals.request_started.connect(close_old_connections)
  43. signals.request_finished.connect(close_old_connections)