"""
Ensure DB connections are not reused after MySQL closes idle sockets.

PyMySQL can raise `InterfaceError(0, "")` when the server drops a connection; Django
will keep the dead connection around until `close_old_connections()` runs.
"""

from __future__ import annotations

from django.db import close_old_connections


class CloseOldDbConnectionsMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        close_old_connections()
        try:
            return self.get_response(request)
        finally:
            close_old_connections()
