PythonでAmazon S3の操作を行う方法(接続編)
PythonでAmazon S3の操作を行う方法(接続編)をご紹介します。
Python向けのAWS SDKである「Boto3」を使用します。
目次
条件
- Python 3.7.0
- Amazon S3
インストール
以下のコマンドでインストールを行います。
pip install boto3
バージョン指定でインストールを行いたい場合、以下のようにします。
pip install boto3==1.0.0
認証資格情報
まずはawsのセキュリティ資格情報を取得する必要があります。
取得手順は、以下の記事の「セキュリティ資格情報」をご参照ください。
認証/構成ファイルに記述する方法
AWS CLIを使用する方法もあるようですが、ここでは認証/構成ファイルに記述する方法で実施します。
WindowsでPythonを実行する場合
ホームドライブとホームパスを確認します。
>echo %HOMEDRIVE% C: >echo %HOMEPATH% \Users\user
credential file
以下のようなパスにファイルを作成します。
~/.aws/credentials
Windowsの場合は以下のパスに作成します。
C:\Users\user\.aws\credentials
記述する内容は以下の通りです。
セキュリティ資格情報で取得した「ACCESS_KEY」および「SECRET_KEY」を記述します。
[default] aws_access_key_id = YOUR_ACCESS_KEY aws_secret_access_key = YOUR_SECRET_KEY
configuration file
以下のようなパスにファイルを作成します。
~/.aws/config
Windowsの場合は以下のパスに作成します。
C:\Users\user\.aws\config
記述する内容は以下の通りです。
[default] region=ap-northeast-1
clientパラメータに渡す方法
clientパラメータに認証資格情報を渡して接続する方法もあります。
以下のようにパラメータで渡しますが、認証情報をプログラムに記述することは推奨されません。
# Do not hard code credentials
client = boto3.client(
's3',
region_name=ap-northeast-1,
# Hard coded strings as credentials, not recommended.
aws_access_key_id='AKIAIO5FODNN7EXAMPLE',
aws_secret_access_key='ABCDEF+c2L7yXeGvUyrPgYsDnWRRC1AYEXAMPLE'
)
PythonによるS3の情報取得
認証/構成ファイルに記述する方法
サンプルソース
以下のようなPythonファイルを作成し、実行します。
S3に接続してバケット一覧を取得しています。
# s3test.py
import boto3
# Let's use Amazon S3
s3 = boto3.resource('s3')
# Print out bucket names
for bucket in s3.buckets.all():
print(bucket.name)
実行結果
バケット名が出力されていることがわかります。
C:\test>python s3test.py 1sample1 C:\test>
clientパラメータに渡す方法
サンプルソース
import logging
import boto3
from botocore.exceptions import ClientError
try:
# Do not hard code credentials
client = boto3.client(
's3',
region_name='ap-northeast-1',
# Hard coded strings as credentials, not recommended.
aws_access_key_id='AKIAIO5FODNN7EXAMPLE',
aws_secret_access_key='ABCDEF+c2L7yXeGvUyrPgYsDnWRRC1AYEXAMPLE'
)
except ClientError as e:
logging.error(e)
# Retrieve the list of existing buckets
response = client.list_buckets()
# Output the bucket names
print('Existing buckets:')
for bucket in response['Buckets']:
print(f' {bucket["Name"]}')
実行結果
バケット名が出力されていることがわかります。
C:\test>python s3test2.py Existing buckets: 1sample1 C:\test>
参考
AWS SDK for Python (Boto3)
https://aws.amazon.com/jp/sdk-for-python/
Boto 3 Documentation
https://boto3.amazonaws.com/v1/documentation/api/latest/index.html
Qiita:AWS リージョン一覧
https://qiita.com/neet244/items/98d408b65134e8ed3918




“PythonでAmazon S3の操作を行う方法(接続編)” に対して2件のコメントがあります。