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 2.3 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. 'backend', 'connection', 'connections', 'router', 'DatabaseError',
  10. 'IntegrityError', 'InternalError', 'ProgrammingError', 'DataError',
  11. 'NotSupportedError', 'Error', 'InterfaceError', 'OperationalError',
  12. 'DEFAULT_DB_ALIAS', 'DJANGO_VERSION_PICKLE_KEY'
  13. ]
  14. connections = ConnectionHandler()
  15. router = ConnectionRouter()
  16. # `connection`, `DatabaseError` and `IntegrityError` are convenient aliases
  17. # for backend bits.
  18. # DatabaseWrapper.__init__() takes a dictionary, not a settings module, so we
  19. # manually create the dictionary from the settings, passing only the settings
  20. # that the database backends care about.
  21. # We load all these up for backwards compatibility, you should use
  22. # connections['default'] instead.
  23. class DefaultConnectionProxy(object):
  24. """
  25. Proxy for accessing the default DatabaseWrapper object's attributes. If you
  26. need to access the DatabaseWrapper object itself, use
  27. connections[DEFAULT_DB_ALIAS] instead.
  28. """
  29. def __getattr__(self, item):
  30. return getattr(connections[DEFAULT_DB_ALIAS], item)
  31. def __setattr__(self, name, value):
  32. return setattr(connections[DEFAULT_DB_ALIAS], name, value)
  33. def __delattr__(self, name):
  34. return delattr(connections[DEFAULT_DB_ALIAS], name)
  35. def __eq__(self, other):
  36. return connections[DEFAULT_DB_ALIAS] == other
  37. def __ne__(self, other):
  38. return connections[DEFAULT_DB_ALIAS] != other
  39. connection = DefaultConnectionProxy()
  40. # Register an event to reset saved queries when a Django request is started.
  41. def reset_queries(**kwargs):
  42. for conn in connections.all():
  43. conn.queries_log.clear()
  44. signals.request_started.connect(reset_queries)
  45. # Register an event to reset transaction state and close connections past
  46. # their lifetime.
  47. def close_old_connections(**kwargs):
  48. for conn in connections.all():
  49. conn.close_if_unusable_or_obsolete()
  50. signals.request_started.connect(close_old_connections)
  51. signals.request_finished.connect(close_old_connections)