| 1 |
from django.core import signals |
| 2 |
from django.db.utils import ( |
| 3 |
DEFAULT_DB_ALIAS, |
| 4 |
DJANGO_VERSION_PICKLE_KEY, |
| 5 |
ConnectionHandler, |
| 6 |
ConnectionRouter, |
| 7 |
DatabaseError, |
| 8 |
DataError, |
| 9 |
Error, |
| 10 |
IntegrityError, |
| 11 |
InterfaceError, |
| 12 |
InternalError, |
| 13 |
NotSupportedError, |
| 14 |
OperationalError, |
| 15 |
ProgrammingError, |
| 16 |
) |
| 17 |
from django.utils.connection import ConnectionProxy |
| 18 |
|
| 19 |
__all__ = [ |
| 20 |
"close_old_connections", |
| 21 |
"connection", |
| 22 |
"connections", |
| 23 |
"reset_queries", |
| 24 |
"router", |
| 25 |
"DatabaseError", |
| 26 |
"IntegrityError", |
| 27 |
"InternalError", |
| 28 |
"ProgrammingError", |
| 29 |
"DataError", |
| 30 |
"NotSupportedError", |
| 31 |
"Error", |
| 32 |
"InterfaceError", |
| 33 |
"OperationalError", |
| 34 |
"DEFAULT_DB_ALIAS", |
| 35 |
"DJANGO_VERSION_PICKLE_KEY", |
| 36 |
] |
| 37 |
|
| 38 |
connections = ConnectionHandler() |
| 39 |
|
| 40 |
router = ConnectionRouter() |
| 41 |
|
| 42 |
# For backwards compatibility. Prefer connections['default'] instead. |
| 43 |
connection = ConnectionProxy(connections, DEFAULT_DB_ALIAS) |
| 44 |
|
| 45 |
|
| 46 |
# Register an event to reset saved queries when a Django request is started. |
| 47 |
def reset_queries(**kwargs): |
| 48 |
for conn in connections.all(initialized_only=True): |
| 49 |
conn.queries_log.clear() |
| 50 |
|
| 51 |
|
| 52 |
signals.request_started.connect(reset_queries) |
| 53 |
|
| 54 |
|
| 55 |
# Register an event to reset transaction state and close connections past |
| 56 |
# their lifetime. |
| 57 |
def close_old_connections(**kwargs): |
| 58 |
for conn in connections.all(initialized_only=True): |
| 59 |
conn.close_if_unusable_or_obsolete() |
| 60 |
|
| 61 |
|
| 62 |
signals.request_started.connect(close_old_connections) |
| 63 |
signals.request_finished.connect(close_old_connections) |