我有一个运行良好的 Django
应用程序。它连接到托管在云端的 MySQL
服务器。
出于安全原因,MySQL
服务器设置为每 30 天自动轮换一次密码。 Django
只有在使用我开发的自定义函数加载 settings.py
时才能访问新密码(这将从 AWS Secrets Manager获取新密码)
).
我正在寻找一种方法让 Django
检测连接是否有问题,然后更新对用户透明的密码。
这可能吗?
最佳答案
我能想到的选项:
- 您可以使用自定义中间件在每个请求之前检查连接。
- 您可以使用
cron
作业定期检查失败的数据库连接,并在发现此类失败时更新设置。
要检查连接,您可以使用方法 django.db.connection.ensure_connection()
。如果你看this answer ,你可以尝试这样的事情:
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
关于python - 与自动旋转密码数据库的 Django 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52924887/