boto3 NoCredentialsError来自AWS提供的代码



我使用过Azure(使用起来很愉快),但需要使用AWS来工作。

我正试图将本地文件发送到s3容器,AWS在文档中提供的代码似乎不起作用。为什么它不起作用,如何解决它?这是基于的Python代码。由于使用pip安装库时出现错误,我确实删除了日志记录。

[https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-uploading-files.html] [1]

import boto3
from botocore.exceptions import ClientError
import os

def upload_file(file_name, bucket, object_name=None):
"""Upload a file to an S3 bucket
:param file_name: File to upload
:param bucket: Bucket to upload to
:param object_name: S3 object name. If not specified then file_name is used
:return: True if file was uploaded, else False
"""
# If S3 object_name was not specified, use file_name
if object_name is None:
object_name = os.path.basename(file_name)
# Upload the file
s3_client = boto3.client('s3')
try:
response = s3_client.upload_file(file_name, bucket, object_name)
except ClientError as e:
return False
return True
upload_file("test.csv", "call-lists")

[1]: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-uploading-files.html

我收到的错误:botocore.exceptions.NoCredentialsError:无法定位凭据

我不知道应该在哪里放置凭据,也不确定需要提供哪些凭据。

如果代码运行在Amazon EC2实例或AWS Lambda函数上,那么您应该分配IAM Role到实例/函数。这将提供代码可以访问的凭据。

如果您在自己的计算机上运行代码(不是EC2实例/Lambda函数),那么您将需要在配置文件中存储凭据。最简单的方法是使用AWS命令行接口(CLI)aws configure命令。

请求一个访问键秘钥. 您可以从安全凭据中获得这些凭据,而不是IAM Identity Center。

如果在本地运行代码,则必须在计算机上正确设置AWS凭据。如何做到这一点,在AWS文档中有详细说明:

  • 配置和凭证文件设置

最新更新