pythonのスクリプトで、AWSのS3にboto3でファイルを転送するときに、MD5チェックをして転送するやり方をメモします。
boto3のインストール
pipコマンドでboto3をインストールします。
pip install boto3
ファイルの転送
putで転送するときに、
ContentMD5オプションに、チェックサム値を入れて破損を確認できます。
破損エラーが起きた場合は、ClientErrorが発生し、response[‘Error’][‘Code’]のBadDigestが入っています。
import boto3
from botocore.exceptions import ClientError
# バケット名
BUCKET_NAME = 'bucket'
# バケットのファイルの転送先
BUCKET_FILE_PATH = 'test.txt'
# S3へ接続
s3 = boto3.resource('s3')
# バケット取得
bucket = s3.Bucuket(BUCKET_NAME)
# オブジェクト取得(ファイルの転送先)
obj = bucket.Object(BUCKET_FILE_PATH)
# S3へ送るファイル
file = open('test.txt', 'rb')
# チェックサム値
checksum = 'EI39GNB02H974B0F8QLB'
try:
# ContentMD5にチェックサム値入れて破損チェックを行う。
response = obj.put(
Body=file,
ContentMD5=checksum,
)
except ClientError as e:
if e.response['Error']['Code'] == 'BadDigest':
# ContentMD5のエラーコードはBadDigest
print('breaked transfer file')
参考
Error Responses – Amazon Simple Storage Service
