如何使用python连接Aurora PostgreSQL Servless实例?

2024-09-26 21:07:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了与PostgreSQL兼容的Amazon Aurora,我知道我想连接该数据库并插入和获取数据,但我无法使用python连接我的AWS Aurora PostgreSQL

我的代码:

def connection_maker(self):
    try:
        ENDPOINT = "assetsintel.cluster-cjeiapuahe69.us-east-1.rds.amazonaws.com"
        PORT = 5432
        USR = "postgres"
        REGION = "us-east-1"
        DBNAME = "assetsintel"
        PASS= "ScottRocks2020!*"

        # gets the credentials from .aws/credentials
        session = boto3.Session(profile_name='default')
        client = session.client('rds')
        print(f'Client: {client}')

        token = client.generate_db_auth_token(DBHostname=ENDPOINT, Port=PORT, DBUsername=USR, Region=REGION)
        print(f'Token: {token}')

        try:
            conn = psycopg2.connect(host=ENDPOINT, port=PORT, database=DBNAME, user=USR, password=token,
                                    sslmode='prefer', sslrootcert="/home/mobin/Downloads/boston_mobin_lus_.pem")
            cur = conn.cursor()
            cur.execute("""SELECT now()""")
            query_results = cur.fetchall()
            print(f'Query results: {query_results}')
        except Exception as e:
            print("Database connection failed due to {}".format(e))

        return None
    except Exception as error:
        logging.error(f'in Creating connection ! {error}')

我在toker打印后卡住了:

错误:

Database connection failed due to could not connect to server: Connection timed out
    Is the server running on host "assetsintel.cluster-cjeiapuahe69.us-east-1.rds.amazonaws.com" (172.31.10.129) and accepting
    TCP/IP connections on port 5432?

Tags: toclienttokenportusrerrorconnectionresults
1条回答
网友
1楼 · 发布于 2024-09-26 21:07:31

如您所见,主机名x.cluster-y.us-east-1.rds.amazonaws.com正在解析为私有ip地址('172.31.xx.xx')。专用Ip地址只能在其自己的网络中使用进行访问

这里可能发生的情况是,当您创建RDS实例时,您必须将其创建为私有实例。因此,无法通过internet访问RDS实例

下面是一些疑难解答提示

  • RDS实例it自配置为可公开访问
  • 确保VPC具有相关的internet网关
  • RDS DB子网应具有到internet网关的路由
  • 最后,RDS安全组应允许来自家庭IP的流量

Here是AWS官方故障排除指南

相关问题 更多 >

    热门问题