【发布时间】:2020-02-19 22:16:08
【问题描述】:
我有一个工作代码可以从 S3 中的一个存储桶下载文件,并在 Python 中完成一些转换工作。我没有在代码中嵌入访问密钥和密钥,但密钥在我的 AWS CLI 配置中。
import boto3
import botocore
BUCKET_NAME = 'converted-parquet-bucket' # replace with your own bucket name
KEY = 'json-to-parquet/names.snappy.parquet' # replace with path and follow with key object
s3 = boto3.resource('s3')
try:
s3.Bucket(BUCKET_NAME).download_file(KEY, 'names.snappy.parquet') # replace the key object name
except botocore.exceptions.ClientError as e: # exception handling
if e.response['Error']['Code'] == "404":
print("The object does not exist.") # if object that you are looking for does not exist it will print this
else:
raise
# Un comment lines 21 and 22 to convert csv to parquet
# dataframe = pandas.read_csv('names.csv')
# dataframe.to_parquet('names.snappy.parquet' ,engine='auto', compression='snappy')
data = pq.read_pandas('names.snappy.parquet', columns=['Year of Birth', 'Gender', 'Ethnicity', "Child's First Name", 'Count', 'Rank']).to_pandas()
#print(data) # this code will print the ALL the data in the parquet file
print(data.loc[data['Gender'] == 'MALE']) # this code will print the data in the parquet file ONLY what is in the query (SQL query)
有人可以帮助我如何在在代码中嵌入访问和密钥或在 AWS 配置中
的情况下让此代码正常工作【问题讨论】:
-
您可以只使用配置文件,从那里导入密钥,然后以这种方式访问它们。
-
@crookedleaf 我根本不想使用访问密钥和密钥,这就是问题的目的
-
啊...我以为您只是不想将它们嵌入到您的代码中。在那种情况下,我认为您无能为力。如果存储桶中的文件是私有且受保护的,那么据我所知,您必须提供这些密钥才能访问它们。类似于尝试使用用户名和密码访问网站但不想提供用户名和密码
-
@crookedleaf 是的,这就是我想要做的,我知道这个问题的开头答案可能是否定的,但我还是试了一下,看看它是否不可能或有任何解决方法
-
您打算在哪里运行此代码?您的笔记本电脑、EC2、Lambda 还是其他地方?而且我认为 S3 对象(文件本身)不是公开可读的。
标签: python amazon-web-services amazon-s3 aws-sdk