boto3をインストール
$ pip3 install boto3
s3にアクセスするための設定がファイル
aws.py
import boto3
s3 = boto3.client(
's3',
aws_access_key_id = {access key},
aws_secret_access_key = {secret_access_key},
region_name = 'ap-northeast-1')
s3_bucket = 'sample-app'
s3を操作するメソッドを作成
services/s3_service.py
from aws import s3, s3_bucket
class S3Service:
# オブジェクトの中身を取得
def get_object():
s3_dir = 'image/sample.json'
sample_json = s3.get_object(Bucket=s3_bucket, Key=s3_dir)
body = sample_json['Body'].read()
print(body.decode('utf-8'))
# 複数のオブジェクト取得
def get_objects(id):
s3_dir = 'image/{0}/'.format(id)
image_objs = s3.list_objects_v2(Bucket=s3_bucket, Prefix=s3_dir)
for image in image_objs['Contents']:
print(image['Key'])
# 複数のオブジェクト削除
def delete_objects(id):
s3_dir = 'image/{0}/'.format(id)
image_objs = s3.list_objects_v2(Bucket=s3_bucket, Prefix=s3_dir)
for obj in image_objs['Contents']:
key = obj['Key']
s3.delete_object(Bucket=s3_bucket, Key=key)
serviceクラスを呼び出す
controller/image_controller.py
from flask import Blueprint, make_response
from services.s3_service import S3Service
# set route
sample_controller = Blueprint('sample_controller_router', __name__)
@sample_controller.route('/delete/<id>', methods=['PUT'])
def delete_images(id):
S3Service.delete_objects(id)
return make_response(jsonify({'code': 200}))