1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Lambda(python)で部品的コードをいろいろ書いてみる

Last updated at Posted at 2018-11-18

GOAL:チートシート的な何か

1.Lambda 関数ハンドラー (Python)

def handler_name(event, context): 
    ...
    return some_value

1.1.テストイベントから値を取得

1.君の名は.testevent
{
  "firstname": "value1",
  "lastname": "value2"
}
1.君の名は.py
import json

def lambda_handler(event, context):
    message = 'Hello {} {}!'.format(event['firstname'], 
                                    event['lastname'])  
    return { 
        'message' : message
    }  

2.boto3

2.1 バケット/キー(ファイル名)が存在するか確認 s3.list_objects

key_exists.py

def lambda_handler(event, context):
    import boto3
    import botocore
  
    s3 = boto3.client('s3')
    
    bucket_name = 'jtakasuryuji-22'
    file_name = 'cat1.png' 
   
    try:
##################################################################
        list_object = s3.list_objects(Bucket=bucket_name, Prefix=file_name)
       
        file_exists = False
        if 'Contents' in list_object:
            message="Found"
            print (message)
        else:
            message="NotFound" #ファイルないんだけど
            print (message)

##################################################################

    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] == 'NoSuchBucket':
            message="NoSuchBucket" #そもそもバケット自体がないんだけど
            print (message)

##################################################################

    return { 
        'message' : message
    }  

ダウンロード用の署名つきURLを取得する generate_presigned_url()

generate_presigned_url.py
def lambda_handler(event, context):
    import boto3
    
    s3 = boto3.client('s3')

    bucket_name = 'jtakasuryuji-22'
    file_name = 'cat1.png' 
 
    header_location = s3.generate_presigned_url(
        ClientMethod = 'get_object',
        Params = {'Bucket' : bucket_name, 'Key' : file_name},
        ExpiresIn = 60,
        HttpMethod = 'GET'
        )
        
    print (header_location)

同一バケット内でファイルをコピー

バケットをまたいでファイルをコピーする

WARNING_NOTWORK_WIP_filecopy_another_bucket.py
    import boto
    conn = boto.connect_s3()

    myBucket = 'jtakasuryuji-22'
    myKey = '20181118b.txt'

    newBucket = 'jtakasuryuji-33'
    
    #copy
    src = conn.get_bucket(myBucket) 
    dst = conn.get_bucket(newBucket) 
    dst.copy_key(mykey,src.name,mykey) 
    

バケット内のファイルを削除する delete_object() object().delete()

deletekey.py

def lambda_handler(event, context):
    import boto3
    
    s3 = boto3.resource('s3')
    myBucket = 'jtakasuryuji-22'
    myKey = '20181118b.txt'
    
#つくる

    #s3_obj = s3.Object(myBucket,myKey)
    #s3_obj.put(Body="")

#消す
    s3.Object(myBucket,myKey).delete()

ファイル名を変更する COPY+DELETE

テキストファイルを新規作成

create_new_file.py

def lambda_handler(event, context):
    import boto3
    
    s3 = boto3.resource('s3')
    myBucket = 'jtakasuryuji-22'
    myKey = '20181118b.txt'
    
#つくる

    s3_obj = s3.Object(myBucket,myKey)
    s3_obj.put(Body="")

#消す
    s3.Object(myBucket,myKey).delete()

boto s3 だけでいっぱいある...

abort_multipart_upload()
can_paginate()
complete_multipart_upload()
copy()
copy_object()
create_bucket()
create_multipart_upload()
delete_bucket()
delete_bucket_analytics_configuration()
delete_bucket_cors()
delete_bucket_encryption()
delete_bucket_inventory_configuration()
delete_bucket_lifecycle()
delete_bucket_metrics_configuration()
delete_bucket_policy()
delete_bucket_replication()
delete_bucket_tagging()
delete_bucket_website()
delete_object()
delete_object_tagging()
delete_objects()
delete_public_access_block()
download_file()
download_fileobj()
generate_presigned_post()
generate_presigned_url()
get_bucket_accelerate_configuration()
get_bucket_acl()
get_bucket_analytics_configuration()
get_bucket_cors()
get_bucket_encryption()
get_bucket_inventory_configuration()
get_bucket_lifecycle()
get_bucket_lifecycle_configuration()
get_bucket_location()
get_bucket_logging()
get_bucket_metrics_configuration()
get_bucket_notification()
get_bucket_notification_configuration()
get_bucket_policy()
get_bucket_policy_status()
get_bucket_replication()
get_bucket_request_payment()
get_bucket_tagging()
get_bucket_versioning()
get_bucket_website()
get_object()
get_object_acl()
get_object_tagging()
get_object_torrent()
get_paginator()
get_public_access_block()
get_waiter()
head_bucket()
head_object()
list_bucket_analytics_configurations()
list_bucket_inventory_configurations()
list_bucket_metrics_configurations()
list_buckets()
list_multipart_uploads()
list_object_versions()
list_objects()
list_objects_v2()
list_parts()
put_bucket_accelerate_configuration()
put_bucket_acl()
put_bucket_analytics_configuration()
put_bucket_cors()
put_bucket_encryption()
put_bucket_inventory_configuration()
put_bucket_lifecycle()
put_bucket_lifecycle_configuration()
put_bucket_logging()
put_bucket_metrics_configuration()
put_bucket_notification()
put_bucket_notification_configuration()
put_bucket_policy()
put_bucket_replication()
put_bucket_request_payment()
put_bucket_tagging()
put_bucket_versioning()
put_bucket_website()
put_object()
put_object_acl()
put_object_tagging()
put_public_access_block()
restore_object()
select_object_content()
upload_file()
upload_fileobj()
upload_part()
upload_part_copy()

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?