Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีเชื่อมต่อ AWS Services ต่างๆ ด้วย Boto3 Library ใน Python


ในบทความนี้ เราจะดูวิธีใช้ Boto3 Library ใน Python เพื่อเชื่อมต่อกับ AWS Services ต่างๆ

ตัวอย่าง

  • เชื่อมต่อกับ AWS S3
  • เชื่อมต่อกับ AWS Glue Job
  • เชื่อมต่อกับ AWS SQS และอื่นๆ อีกมากมาย

ขั้นตอนการแก้ปัญหา

  1. ขั้นตอนที่ 1 – สร้าง AWS Session ด้วย Boto3 Library
  2. ขั้นตอนที่ 2 – ส่ง AWS Service Name ใน client เพื่อเข้าถึง Low-level Service Access หรือ ส่ง AWS Service Name ใน resource เพื่อเข้าถึง High-level Object-oriented Service Access / High-level Interface

ตัวอย่างโค้ด

โค้ดต่อไปนี้เชื่อมต่อกับ AWS Services ต่างๆ:

import boto3

# To get AWS Client
def get_connection_aws_client(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(get_connection_aws_client('s3'))   # for s3 connection
print(get_connection_aws_client('glue')) # for glue connection
print(get_connection_aws_client('sqs'))  # for sqs connection and other services

# To get AWS Resource
def get_connection_aws_resource(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(get_connection_aws_resource('s3'))  # for s3 connection
print(get_connection_aws_resource('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 ไม่รองรับทุก Service ในการเชื่อมต่อ เช่น หากผู้ใช้พยายามเชื่อมต่อ Glue Service โดยใช้ resource AWS จะโยน Exception ดังนี้ –

boto3.exceptions.ResourceNotExistsError: The 'glue' resource does not exist.

พิจารณาใช้ boto3.client('glue') แทน Resource สำหรับ 'glue'

Services ต่อไปนี้รองรับโดย Resource –

  • cloudformation
  • cloudwatch
  • dynamodb
  • ec2
  • glacier
  • iam
  • opsworks
  • s3
  • sns
  • sqs