如何连接到 moto mysql 实例?

How can I connect to a moto mysql instance?

我使用模拟的 boto3 rds 客户端创建了一个 RDS 数据库实例。这是我在 conftest.py

中的设置方式
@pytest.fixture
def aws_credentials():
    """Mocked AWS Credentials for moto."""
    os.environ["AWS_ACCESS_KEY_ID"] = "testing"
    os.environ["AWS_SECRET_ACCESS_KEY"] = "testing"
    os.environ["AWS_SECURITY_TOKEN"] = "testing"
    os.environ["AWS_SESSION_TOKEN"] = "testing"

@pytest.fixture
def rds_client(aws_credentials, aws_region):
    with mock_rds():
        client = boto3.client("rds", region_name=aws_region)
        yield client

按照此处的示例 (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.Connecting.Python.html),我这样设置 mysql 连接器:

db_instance = rds_client.create_db_instance(DBInstanceIdentifier="TestDBInstanceIdentifier",
                                            DBInstanceClass="db.m4.large", Engine="mysql",
                                            MasterUsername="root", DBName="TestDBName")
print("RDS Instance-----------------------------------------------------")
print(db_instance)

host = db_instance['DBInstance']['Endpoint']['Address']
port = db_instance['DBInstance']['Endpoint']['Port']
user = db_instance['DBInstance']['MasterUsername']
dbname = db_instance['DBInstance']['DBName']
print("Starting connection")
token = rds_client.generate_db_auth_token(DBHostname=host, Port=port, DBUsername=user, Region=aws_region)

mydb = mysql.connector.connect(host=host, database=dbname, user=user, passwd=token, port=port)

但是,连接器找不到数据库:

FAILED test_read_rds_db - mysql.connector.errors.DatabaseError: 2005 (HY000): Unknown MySQL server host 'TestDBInstanceIdentifier.aaaaaaaaaa.us-east-1.rds.amazonaws.com' (8)

以前有人设置过吗?

Moto 不提供此功能。它模拟 AWS API,但不公开任何 RDBMS-functionality.

您可以改为查看 Localstack。它在后台使用 Moto 来模拟对 AWS 的调用,但提供了最重要的功能,例如连接到 RDS 实例的能力。 请参阅此处的文档:https://docs.localstack.cloud/aws/rds/