[[AWSメモ]] >
* AWS LambdaからS3へのアップロードとダウンロード [#oba8584c]
#setlinebreak(on);
** アップロードとダウンロード [#q990b8b1]
#html(<div style="padding-left:10px">)
#mycode2(){{
from __future__ import print_function
import boto3
import zipfile
def lambda_handler(event, context):
print('s3UploadDownload : START')
bucket_name = 'uploaded-files1'
#-------------------------------------
# テキストファイルをアップロード
#-------------------------------------
file_key = 'test1.txt'
text = 'Test001' + "\n" \
+ 'Test002' + "\n" \
+ 'Test003' + "\n" \
+ 'Test004' + "\n" \
+ 'Test005'
# S3にアップロード
res = upload_file(bucket_name, file_key, bytes(text, 'UTF-8'))
print ("## data : START ##")
print (res)
print ("## data : END ##")
# S3から取得
res = download_file(bucket_name, file_key)
print ("## data : START ##")
print (res.decode('utf-8'))
print ("## data : END ##")
#-------------------------------------
# zipファイルをアップロード
#-------------------------------------
file_key = 'test1.zip'
tmp_text_file = '/tmp/test1.txt'
tmp_zip_file = '/tmp/test1.zip'
# テキストファイル作成
with open(tmp_text_file, 'w') as f:
f.write(text)
f.close()
# zipファイル作成
with zipfile.ZipFile(tmp_zip_file, 'w', zipfile.ZIP_DEFLATED) as f:
f.write(tmp_text_file, 'test1.txt')
f.close()
# S3にアップロード
with open(tmp_zip_file, 'rb') as f:
zip_data = f.read()
res = upload_file(bucket_name, file_key, zip_data)
print ("## data : START ##")
print (res)
print ("## data : END ##")
# S3から取得
res = download_file(bucket_name, file_key)
print ("## data : START ##")
print (res)
print ("## data : END ##")
print('s3UploadDownload : END')
return 'Hello from s3UploadDownload'
# S3にアップロード
def upload_file(bucket_name, file_key, bytes):
s3 = boto3.resource('s3')
s3Obj = s3.Object(bucket_name, file_key)
res = s3Obj.put(Body = bytes)
return res
# S3からダウンロード
def download_file(bucket_name, file_key):
s3 = boto3.resource('s3')
s3Obj = s3.Object(bucket_name, file_key)
return s3Obj.get()['Body'].read()
}}
#html(</div>)