Django connection with an Auto-rotate password DB

Viewed 710

I have a Django application that is working perfectly. It's connected to a MySQL server hosted on the cloud.

The MySQL server is set to auto-rotate the password every 30 days for security reasons. Django can access the new password only when settings.py is loaded using a custom function I have developed (that will fetch the new password from AWS Secrets Manager).

I'm looking for a way to allow Django to detect if a connection has a problem then update the password all transparent to the user.

Is that possible?

1 Answers

Options I can think of:

  1. You could use a custom middleware that checks the connection before each request.
  2. You could use a cron job that periodically checks for failed database connections, and updates the settings if it finds such a failure.

To check for connections you can use the method django.db.connection.ensure_connection(). If you look at this answer, you could try something like this:

from django.db import connection
from django.db.utils import OperationalError

class Command(BaseCommand):
    def handle(self, *args, **options):
        try:
            # if this succeeds, no further action is needed
            connection.ensure_connection()
        except OperationalError:
            # update the DB password and try again
Related