Django 连接自动轮换密码数据库

Kha*_*ail 7 python mysql passwords django

我有一个Django运行完美的应用程序。它连接到MySQL云上托管的服务器。

出于安全原因,服务器MySQL设置为每 30 天自动轮换一次密码。仅当使用我开发的自定义函数(将从中获取新密码)加载Django时才能访问新密码。settings.pyAWS Secrets Manager

我正在寻找一种方法来检测Django连接是否有问题,然后更新对用户完全透明的密码。

那可能吗?

Ral*_*alf 0

我能想到的选项:

  1. 您可以使用自定义中间件在每个请求之前检查连接。
  2. 您可以使用cron定期检查失败的数据库连接的作业,并在发现此类失败时更新设置。

要检查连接,您可以使用该方法django.db.connection.ensure_connection()。如果你看看这个答案,你可以尝试这样的事情:

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
Run Code Online (Sandbox Code Playgroud)