__init__.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. from django.utils.connection import ConnectionProxy
  9. __all__ = [
  10. 'connection', 'connections', 'router', 'DatabaseError', 'IntegrityError',
  11. 'InternalError', 'ProgrammingError', 'DataError', 'NotSupportedError',
  12. 'Error', 'InterfaceError', 'OperationalError', 'DEFAULT_DB_ALIAS',
  13. 'DJANGO_VERSION_PICKLE_KEY',
  14. ]
  15. connections = ConnectionHandler()
  16. router = ConnectionRouter()
  17. # For backwards compatibility. Prefer connections['default'] instead.
  18. connection = ConnectionProxy(connections, DEFAULT_DB_ALIAS)
  19. # Register an event to reset saved queries when a Django request is started.
  20. def reset_queries(**kwargs):
  21. for conn in connections.all():
  22. conn.queries_log.clear()
  23. signals.request_started.connect(reset_queries)
  24. # Register an event to reset transaction state and close connections past
  25. # their lifetime.
  26. def close_old_connections(**kwargs):
  27. for conn in connections.all():
  28. conn.close_if_unusable_or_obsolete()
  29. signals.request_started.connect(close_old_connections)
  30. signals.request_finished.connect(close_old_connections)