"Getting Started with AWS and Python"をboto3で試す その1

AWS SDKを触ったことがなかったので、Python向けのSDKであるbotoをAWSのサイトにあるtutorialを参考に試してみます。botoはバージョンアップされており、現行の最新バージョンはboto3となっているので、その点を考慮しつつ勉強。

tutorialのページはこちら。

https://aws.amazon.com/jp/articles/getting-started-with-aws-and-python/?tag=articles%23keywords%23amazon-sqs

こっちはboto3のreferenceね。

Boto 3 Documentation — Boto 3 Docs 1.6.19 documentation

とりあえず、awscliとbotoをインストール。

$ pip install awscli
$ pip install boto3
$ pip freeze | grep -e aws -e boto
awscli==1.14.16
boto3==1.5.6
botocore==1.8.20

awsのクレデンシャル情報を登録。今回は何も考えずにAdmin権限を与えたIAMユーザを設定しています。

$ aws configure
AWS Access Key ID [None]: XXXXXXXXXXXXXXXXX
AWS Secret Access Key [None]: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Default region name [None]: ap-northeast-1
Default output format [None]:
$ aws configure list
      Name                    Value             Type    Location
      ----                    -----             ----    --------
   profile                <not set>             None    None
access_key     ****************QU7A shared-credentials-file
secret_key     ****************oOmg shared-credentials-file
    region           ap-northeast-1      config-file    ~/.aws/config

尚、boto3には以下5つの主要機能があるとのこと。高レベルAPIオブジェクト指向のResourcesと、昔から低レベルAPIのClientsがあります。今回は、高レベルAPIであるResourcesにて処理を書いてみます。

  • Resources
    • an object-oriented interface to Amazon Web Services (AWS). They provide a higher-level abstraction than the raw, low-level calls made by service clients.
  • Collections
    • an iterable interface to a group of resources. Collections behave similarly to Django QuerySets and expose a similar API. A collection seamlessly handles pagination for you, making it possible to easily iterate over all items from all pages of data.
  • Clients
    • a low-level interface to AWS whose methods map close to 1:1 with service APIs. All service operations are supported by clients. Clients are generated from a JSON service definition file.
  • Paginators
    • Some AWS operations return results that are incomplete and require subsequent requests in order to attain the entire result set. The process of sending subsequent requests to continue where a previous request left off is called pagination.
  • Waiters
    • a way to block until a certain state has been reached.

S3をいじってみるぞ。bucketをつくろう。

> import boto3
> s3 = boto3.resource('s3')
> s3.create_bucket(Bucket='mybucket-kiritanperopero', CreateBucketConfiguration={'LocationConstraint': 'ap-northeast-1'})
s3.Bucket(name='mybucket-kiritanperopero')

つづいて、objectをつくるぞ。

> object = s3.Object('mybucket-kiritanperopero', 'tmp/zunda.txt')
> body = u'ずんねえさま'
> object.put(Body=body)

つくったobjectの中身を見るぞ。

> object.get()['Body'].read().decode('utf-8')
'ずんねえさま'