我试图编写一个Python脚本来访问amazonredshift,在Redshift中创建一个表,并将数据从S3复制到Redshift表。在
我的代码是:
import psycopg2
import os
#import pandas as pd
import requests
requests.packages.urllib3.disable_warnings()
redshift_endpoint = os.getenv("END-point")
redshift_user = os.getenv("user")
redshift_pass = os.getenv("PASSWORD")
port = 5439
dbname = 'DBNAME'
conn = psycopg2.connect(
host="",
user='',
port=5439,
password='',
dbname='')
cur = conn.cursor()
aws_key = os.getenv("access_key") # needed to access S3 Sample Data
aws_secret = os.getenv("secret_key")
#aws_iam_role= os.getenv('iam_role') #tried using this too
base_copy_string= """copy %s from 's3://mypath/%s'.csv
credentials 'aws_access_key_id= %s aws_access_secrect_key= %s'
delimiter '%s';""" # the base COPY string that we'll be using
#easily generate each table that we'll need to COPY data from
tables = ["employee"]
data_files = ["test"]
delimiters = [","]
#the generated COPY statements we'll be using to load data;
copy_statements = []
for tab, f, delim in zip(tables, data_files, delimiters):
copy_statements.append(base_copy_string % (tab, f, aws_key, aws_secret, delim)%)
#create Table
cur.execute(""" create table employee(empname varchar(30),empno integer,phoneno integer,email varchar(30))""")
for copy_statement in copy_statements: # execute each COPY statement
cur.execute(copy_statement)
conn.commit()
for table in tables + ["employee"]:
cur.execute("select count(*) from %s;" % (table,))
print(cur.fetchone())
conn.commit() # make sure data went through and commit our statements permanently.
当我运行这个命令时,在当前执行(抄送泳声明)
^{pr2}$我的代码有问题吗?或者是AWS访问的关键问题?在
我甚至尝试使用iam_角色,但出现了一个错误:
IAM role cannot assume role even in Redshift
通过附加S3FullAccess策略,我拥有托管IAM角色权限。在
首先,从不、从不、从不在代码中硬编码访问密钥和密钥。所以排除了你的第一个查询。现在要采取正确的方法来实现事情。你说得对,我的角色是正确的。不幸的是,我不能从你的描述中得到准确的错误和用例。据我所知,您正在尝试从您的计算机(本地计算机)运行这个python文件。因此,您需要向您的IAM用户附加权限才能访问RedShift(以及您的代码所涉及的所有其他服务)。如果我的假设错了,请纠正我。在
你的脚本中有一些错误。在
1)更改基\u copy_string,如下所示:
必须在凭据中添加}。在
;
,并且还存在其他带有单引号的格式问题。它是aws_secret_access_key
而不是{查看此链接以获取详细信息:http://docs.aws.amazon.com/redshift/latest/dg/copy-usage_notes-access-permissions.html#copy-usage_notes-iam-permissions
我建议您使用iam角色而不是凭据。 http://docs.aws.amazon.com/redshift/latest/dg/loading-data-access-permissions.html
2)更改复制_语句.append如下(最后去掉多余的
%
):请更正这些错误,然后再试一次。在
万一你错过了 安装AWS CLI 跑 aws配置 把你的证件和地区 希望这有帮助。在
相关问题 更多 >
编程相关推荐