gpt4 book ai didi

flask - botocore.exceptions.NoCredentialsError : Unable to locate credentials , 即使在手动传递凭据后

转载 作者:行者123 更新时间:2023-12-03 16:17:58 48 4
gpt4 key购买 nike

嗨,我是创建 Flask 应用程序的新手,我创建了一个小 GUI 来将文件上传到 S3 Bucket
这是处理相同的代码片段

s3 = boto3.client('s3', region_name="eu-west-1", 
endpoint_url=S3_LOCATION, aws_access_key_id=S3_KEY, aws_secret_access_key=S3_SECRET)

myclient = boto3.resource('s3')
file = request.files['file[]']
filename=file.filename
data_files = request.files.getlist('file[]')
for data_file in data_files:
file_contents = data_file.read()
ts = time.gmtime()
k=time.strftime("%Y-%m-%dT%H:%M:%S", ts)
name=filename[0:-4]
newfilename=(name+k+'.txt')
myclient.Bucket(S3_BUCKET).put_object(Key=newfilename,Body=file_contents)
message='File Uploaded Successfully'
print('upload Successful')

当我从我的本地系统测试它时,该部分工作正常,但在将其上传到 EC2 实例时,该部分
myclient.Bucket(S3_BUCKET).put_object(Key=newfilename,Body=file_contents)

是抛出错误的地方:

botocore.exceptions.NoCredentialsError: Unable to locate credentials



我创建了一个文件 config.py,我在其中存储所有凭据并在运行时传递它们。
不确定是什么导致 EC2 实例出错,请帮我解决

最佳答案

您可能是 confusing boto3 service resource and client .

#!!!! this instantiate an object call s3 to boto3.s3.client with credential  
s3 = boto3.client('s3', region_name="eu-west-1",
endpoint_url=S3_LOCATION, aws_access_key_id=S3_KEY, aws_secret_access_key=S3_SECRET)

#!!!! this instantiate an object call myclient to boto3.s3.resource that use
# credential inside .aws folder, since no designated credential given.
myclient = boto3.resource('s3')

似乎您尝试将显式凭证传递给 boto3.resource 而不使用 .aws/credential 和 .aws/default 访问 key 。如果是这样,这不是正确的方法。要将凭证显式传递给 boto3.resource,建议使用 boto3.Session(这也适用于 boto3.client)。这还允许您使用初始化 session 连接到不同的 AWS 服务,而不是在程序中为不同的服务传递 API key 。
import boto3
session = boto3.session(
region_name = 'us-west-2',
aws_access_key_id=S3_KEY,
aws_secret_access_key=S3_SECRET)

# now instantiate the services
myclient = session.resource('s3')
# .... the rest of the code

不过,更好的方法是使用 .aws 凭证。因为在代码中硬编码任何访问 key /密码是一种不好的做法。如果您需要访问不同地区的不同 API key ,也可以使用配置文件名称调用。例如

~/.aws/凭证
[default]
aws_access_key_id = XYZABC12345
aws_secret_access_key = SECRET12345

[appsinfinity]
aws_access_key_id = XYZABC12346
aws_secret_access_key = SECRET12346

~/.aws/config
[默认]
地区 = us-west-1
[profile appsinfinity] 
region = us-west-2

和代码
import boto3
app_infinity_session = boto3.session(profile_name= 'appsinfinity')
....

关于flask - botocore.exceptions.NoCredentialsError : Unable to locate credentials , 即使在手动传递凭据后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49970730/

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com