How to automatically refresh azure access token using Django

I have a django web app that connects to a mssql database on azure using a user assigned managed identity. The app use DefaultAzureCredential from azure.identity to get a azure token for the managed identity. However, after a while the token expires, the app cannot connect to the database anymore. How to automatically refresh the azure access token properly?
In settings.py,

def get_token():
    credential = DefaultAzureCredential(managed_identity_client_id = 'my-managed-identity-client-id')
    token = credential.get_token("https://database.windows.net/.default")
    return token.token
DATABASES = {
    'default': {
        'ENGINE': 'mssql',
        'NAME': 'my-db-name',
        'HOST': 'server-name',
        'PORT': '1433',
        "TOKEN": get_token(),
        'OPTIONS': {
            'driver': 'ODBC Driver 17 for SQL Server',
        },
    }
}

I tried some middleware approaches, but all failed to refresh the token eventually.

I have the same scenario just that i’m trying to connect to Postgres db. Any ideas on this?

I ran into this problem as well!

My solution was to extend the database engine with a very thin wrapper to handle token rotation.

So in settings.py we have

"ENGINE": "<path_to_my_custom_db_engine>",

And then in <path_to_my_custom_db_engine>/base.py we can lightly modify the behavior of the default Database engine. So a pretty blunt approach is like:

class MyDatabaseWrapper(DatabaseWrapper):
    def get_connection_params(self):
        azure_credential = DefaultAzureCredential()
        token = azure_credential.get_token("URL to get the token from")
        self.settings_dict["PASSWORD"] = get_token().token
        return super().get_connection_params()

Note that DefaultAzureCredential get_token handles some expiration logic for us. It will cache a valid token, fetch a new token if the old token is either expired or near expiration.