与自动旋转密码数据库的 Django 连接
Django connection with an Auto-rotate password DB
我有一个运行良好的 Django
应用程序。它已连接到云端托管的 MySQL
服务器。
出于安全原因,MySQL
服务器设置为每 30 天自动轮换一次密码。 Django
只有在使用我开发的自定义函数加载 settings.py
时才能访问新密码(将从 AWS Secrets Manager
获取新密码)。
我正在寻找一种允许 Django
检测连接是否有问题然后更新密码的方法,这对用户来说是透明的。
这可能吗?
我能想到的选项:
- 您可以使用自定义中间件在每次请求之前检查连接。
- 您可以使用
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
我有一个运行良好的 Django
应用程序。它已连接到云端托管的 MySQL
服务器。
出于安全原因,MySQL
服务器设置为每 30 天自动轮换一次密码。 Django
只有在使用我开发的自定义函数加载 settings.py
时才能访问新密码(将从 AWS Secrets Manager
获取新密码)。
我正在寻找一种允许 Django
检测连接是否有问题然后更新密码的方法,这对用户来说是透明的。
这可能吗?
我能想到的选项:
- 您可以使用自定义中间件在每次请求之前检查连接。
- 您可以使用
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