7

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?

Ralf
  • 16,086
  • 4
  • 44
  • 68

1 Answers1

0

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
Ralf
  • 16,086
  • 4
  • 44
  • 68
  • I tried option 1 and it worked. However, the first request that passes through the middleware when the DB password is incorrect the user gets an access denied error. When the user refreshes the page it provides the expected result. Any ideas? – Khalid Alhokail Oct 23 '18 at 16:41
  • In which position is your custom middleware inside the list `MIDDLEWARE`? Maybe another middleware is accessing the database before your middleware is called? – Ralf Oct 23 '18 at 16:53
  • Sorry, it's working now. This is my first middleware in Django and I had the line: response = self.get_response(request) as the first line in code. In my case, I moved it to the end of the code and worked perfectly. In terms of Middleware order, it was originally the first one. – Khalid Alhokail Oct 23 '18 at 17:54