$ pip3 install boto3
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'
services/s3_service.py
from aws import s3, s3_bucket
class S3Service:
#Get the contents of an object
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'))
#Get multiple objects
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'])
#Delete multiple objects
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)
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}))
Recommended Posts