如何使用 Python 中的 Boto3 庫連線不同的 AWS 服務?


在本文中,我們將瞭解如何使用 Python 中的 Boto3 庫連線不同的 AWS 服務。

示例

  • 連線 AWS S3。

  • 連線 AWS Glue 作業

  • 連線 AWS SQS 等等。

解決此問題的方法/演算法

步驟 1 - 使用 Boto3 庫建立一個 AWS 會話。

步驟 2 - 將 AWS 服務名稱傳遞給 client 以獲取低階服務訪問許可權。

或者,將 AWS 服務名稱傳遞給 resource 以獲取高階面向物件的 服務訪問許可權/高階介面。

示例

以下程式碼連線不同的 AWS 服務:

import boto3
# To get AWS Client
def getconnection_AWSClient(service_name):
   session = boto3.session.Session()
   # User can pass customized access key, secret_key and token as well
   s3_client = session.client(service_name)
   return s3_client
print(getconnection_AWSClient('s3')) # for s3 connection
print(getconnection_AWSClient('glue')) # for glue connection
print(getconnection_AWSClient('sqs')) # for sqs connection and other services

# To get AWS Resource
def getconnection_AWSResource(service_name):
   session = boto3.session.Session()
   # User can pass customized access key, secret_key and token as well
   s3_resource = session.resource(service_name)
   return s3_resource

print(getconnection_AWSResource('s3')) # for s3 connection
print(getconnection_AWSResource('sqs')) # for sqs connection and other services

輸出

<botocore.client.S3 object at 0x00000216C4CB89B0>
<botocore.client.Glue object at 0x00000216C5129358>
<botocore.client.SQS object at 0x00000216C4E03E10>
s3.ServiceResource()
sqs.ServiceResource()

請注意,resource 並不支援所有服務的連線。例如,如果使用者嘗試使用resource連線 Glue 服務,則 AWS 會丟擲以下異常:

boto3.exceptions.ResourceNotExistsError: 'glue' 資源不存在。

請考慮使用 boto3.client('glue') 代替 'glue' 的 resource

以下服務受 resource 支援:

  • cloudformation

  • cloudwatch

  • dynamodb

  • ec2

  • glacier

  • iam

  • opsworks

  • s3

  • sns

  • sqs

更新於:2021年3月22日

626 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告