如何在 Python 中使用 Boto3 库连接不同的 AWS 服务?
在本文中,我们将了解如何使用Python中的Boto3库连接不同的AWS服务。
例子
与AWSS3连接。
连接AWSGlue作业
连接AWSSQS等等。
解决这个问题的方法/算法
步骤1-使用Boto3库创建AWS会话。
步骤2-在客户端中传递AWS服务名称以获得低级服务访问。
或者,在资源中传递AWS服务名称以获取高级面向对象服务访问/高级接口。
示例
以下代码连接不同的AWS服务-
import boto3 #获取AWS客户端 def getconnection_AWSClient(service_name): session = boto3.session.Session() #用户也可以传递自定义的访问密钥、secret_key和令牌 s3_client = session.client(service_name) return s3_client print(getconnection_AWSClient('s3')) #用于s3连接 print(getconnection_AWSClient('glue')) #用于胶水连接 print(getconnection_AWSClient('sqs')) #用于sqs连接和其他服务 #获取AWS资源 def getconnection_AWSResource(service_name): session = boto3.session.Session() #用户也可以传递自定义的访问密钥、secret_key和令牌 s3_resource = session.resource(service_name) return s3_resource print(getconnection_AWSResource('s3')) #用于s3连接 print(getconnection_AWSResource('sqs')) #用于sqs连接和其他服务输出结果
s3.ServiceResource() sqs.ServiceResource()
请注意,资源不支持连接所有服务。例如,如果用户尝试使用资源连接胶水服务,那么AWS会抛出以下异常-
boto3.exceptions.ResourceNotExistsError:“胶水”资源不存在。
考虑使用boto3.client('glue')而不是'glue'的资源
以下服务由资源支持-
云的形成
云表
动态数据库
ec2
冰川
我是
运营商
s3
网络安全
平方