【问题标题】:Failed to connect to Redshift Database usng Boto3 and Psycopg2使用 Boto3 和 Psycopg2 连接到 Redshift 数据库失败
【发布时间】:2019-09-04 16:28:22
【问题描述】:

我的 python 代码无法使用 Boto3 api 和 psycopg2 库连接到 Redshift 数据库

让我问一下连接到数据库的问题。我不拥有它。我正在尝试使用 Boto3 来获取_cluster_credentials。我的代码无法连接到数据库,我认为这是一个授权问题,但我很可能是错的,不确定。你能看看我写的代码,然后告诉我它们看起来是否还可以,或者我是否遗漏了一些完全可能的东西。当我运行它时,会打印最后一行。

import boto3
import psycopg2

client = boto3.client(service_name='redshift', region_name='us-east-1')

cluster_creds = client.get_cluster_credentials(
    DbUser='#######',
    DbName='##########',
    ClusterIdentifier='########redshift',
    password = clusster_creds['DbPassword'],
    AutoCreate=False)

try:
    conn = psycopg2.connect(
        host = '########-redshift.#####.us-east-1.redshift.amazonaws.com',
        prt = '5439',
        user = cluster_creds['DbUser'],
        database = 'DbName' )

    #Verify connection
    cursor = conn.cursor()
    cursor.execute("SELECT VERSION()")
    results = cursor.fetchone()
    ver=results[0]

    if (ver is None):
        print("Could not find version")
    else:
        print("The version is " + ver)

except:
    print("Failed to open database connection - James")

我想我应该看到“版本是”,而不是“无法打开数据库...”

【问题讨论】:

  • 你知道这个集群是否在防火墙后面吗?
  • 您需要为conn = psycopg2.connect 行指定密码。好像缺少密码参数

标签: python-3.x database-connection amazon-redshift boto3 psycopg2


【解决方案1】:

我遇到了类似的问题。我想问题出在您使用的 psycopg2 软件包上。

背景

如果您确定此解决方案对您有帮助-

  1. 您已正确配置 IAM 角色。
  2. 您的 VPC 配置完美,但您无法连接到 RS 数据库。

解决方案

所以,最后我发现了问题 - 我使用的 psycopg2 构建与 AWS lambda 函数不兼容。所以,这就是我所做的-

  • 使用 pip 安装了 psycopg2。确保您使用 linux 操作系统 执行此步骤,因为 lambda 的执行环境使用 Linux。
pip3 install psycopg2 -t ./
  • 为 lambda 创建了一个部署包并将其上传到您的 lambda。

PS- 使用 Linux 构建 psycopg 包是关键。

【讨论】:

  • 你能分享一下 psycopg2 的 zip 文件吗?
【解决方案2】:

试试这个代码,它对我有用,你不需要 boto3,它是 S3 的。

import psycopg2

try:
    con = psycopg2.connect(
        dbname="####",
        host="####",
        port="5439",
        user="####",
    password="####",
)

    cursor = con.cursor()
    cursor.execute("SELECT VERSION()")
    results = cursor.fetchone()
    ver=results[0]

    if (ver is None):
        print("Could not find version")
    else:
        print("The version is " + ver)

except:
    print("Failed to open database connection - James")


con.close()

如果您的集群位于防火墙后面,您将需要 sshtunnel 我也可以提供帮助。

【讨论】:

  • 是的,我相信它确实有防火墙。我有一个 IAM 角色、主数据库用户名、集群名称、数据库名称,但我没有主密码。这就是为什么我尝试使用 get_cluster_credential 方法创建一个临时的。
  • 我没有创建集群,我的老板做了。我认为这是附加到我的帐户的权限问题,或者需要带有访问/秘密密钥的配置/凭据文件或某种方式将用户名和密码链接到我的角色或用户帐户配置文件。我正在使用 MoabXterm 或 Putty 通过 SSH 连接连接到 EC2 实例。
【解决方案3】:

我能够通过 Python、Boto3 和 Psycopg2 API 连接到 AWS Redshift,获取临时用户凭证并在 Redshift 中创建表。我还将数据从 S3 存储桶复制到该 Redshift 表。为了更好的可读性,我将代码分开。

我要感谢 Stack Overflow 上的 @demicioglu 和达拉斯/沃思堡 Postgres 聚会小组的 Jessica Sharp,他们在以下位置提供了示例: https://github.com/sharpDBA/redshift_demo

db.Conn # connection information
host = '#####-redshift.#####.us-east-1.redshift.amazonaws.com'
port = 5439
database = '#####'
db.Cred # Credential information
import boto3
import psycopg2
import sys

DB_NAME = '######'
CLUSTER_IDENTIFIER = '######-redshift'
DB_USER = '#####'

try:
  client = boto3.client('redshift', region_name='us-east-1')

  #get cluster credentials and temp username and password
  cluster_creds = client.get_cluster_credentials(
       DbUser=DB_USER, DbName=DB_NAME, ClusterIdentifier=CLUSTER_IDENTIFIER, AutoCreate=False)
  temp_user = cluster_creds['DbUser']
  temp_pswd = cluster_creds['DbPassword']

   #report any errors
except Exception as ex:
    print("Exception name : " + ex.__class__.__name__)
    print(str(ex))
    print("Failed to open connection to Redshift database")
    sys.exit(1)
db.CreateTbl # Create table in Redshift
import psycopg2
import dbCred
import dbConn
import sys

# Set Redshift cluster connection details
def CreateTable(schema, tblName):
    schema=schema
    tblName=tblName

    try:
        # Get AWS Redshift connection attributes
        dbname = dbConn.database
        host = dbConn.host
        port = dbConn.port

        # Get temporary database credentials
        user = dbCred.temp_user
        password = dbCred.temp_pswd

        # Connect to AWS Redshift database
        connect = psycopg2.connect(database=dbname,
                                   host=host,
                                   port=port,
                                   user=user,
                                   password=password)

        cur = connect.cursor()

        # SQL Query

        cur.execute("CREATE TABLE " + schema + "." + tblName + " "
                    "(vendorid varchar(4), pickup_datetime TIMESTAMP, "
                    "dropoff_datetime TIMESTAMP, store_and_fwd_flag varchar(1), "
                    "ratecode int, pickup_longitude float(4), pickup_latitude float(4),"
                    "dropoff_logitude float(4), dropoff_latitude float(4), "
                    "passenger_count int, trip_distance float(40), fare_amount float(4), "
                    "extra float(4), mta_tax float(4), tip_amount float(4), "
                    "tolls_amount float(4), ehail_fee float(4), improvement_surcharge float(4), "
                    "total_amount float(4), payment_type varchar(4), trip_type varchar(4)) "
                    "DISTSTYLE EVEN SORTKEY (passenger_count, pickup_datetime);")

        connect.commit()

        #report any errors
    except Exception as ex:
        print("Exception name : " + ex.__class__.__name__)
        print(str(ex))
        print("Failed to open connection to Redshift database")
        sys.exit(1)

    #close all connections
    finally:
        cur.close()
        connect.close()

if __name__ == "__main__":
    if (len(sys.argv) != 3):
        print("Usage: " + sys.argv[0] + "<SchemaName>" + "<TableName>")
        sys.exit(1)
    else:
        schema = sys.argv[1]
        tblName = sys.argv[2]

    CreateTable(schema, tblName)

【讨论】:

    猜你喜欢
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 2012-06-26
    • 2019-12-14
    • 2016-09-24
    • 2021-07-14
    相关资源
    最近更新 更多