Skip to content

Instantly share code, notes, and snippets.

@wifecooky
Forked from taogawa/gist:5613314
Last active July 27, 2019 16:04
Show Gist options
  • Save wifecooky/78319eb3f941aaa85a560a843ebc51ea to your computer and use it in GitHub Desktop.
Save wifecooky/78319eb3f941aaa85a560a843ebc51ea to your computer and use it in GitHub Desktop.
[AWS] S3を使う(Python) #aws
# coding: utf-8
# バケットにファイルを作成する
import boto
from boto.s3.connection import S3Connection
from boto.s3.key import Key
AWS_KEY_ID = 'aws_key_id'
AWS_SECRET_KEY = 'aws_secret_key'
BUCKET_NAME = 'bucket_name'
conn = S3Connection(AWS_KEY_ID, AWS_SECRET_KEY)
bucket = conn.get_bucket(BUCKET_NAME)
# ディレクトリを作る
# 末尾がスラッシュならばディレクトリができる
key1 = bucket.new_key('test/')
key1.set_contents_from_string('')
# ディレクトリ配下にファイルを作成する
key2 = bucket.new_key('test/a.txt')
key2.set_contents_from_string('foo')
# coding: utf-8
# ダウンロードURLの生成
import boto
from boto.s3.connection import S3Connection
from boto.s3.key import Key
AWS_KEY_ID = 'aws_key_id'
AWS_SECRET_KEY = 'aws_secret_key'
BUCKET_NAME = 'bucket_name'
conn = S3Connection(AWS_KEY_ID, AWS_SECRET_KEY)
bucket = conn.get_bucket(BUCKET_NAME)
# 有効期限が60秒の署名付きURLを生成する
key = bucket.get_key('foo.txt')
url = key.generate_url(60)
print url
# coding: utf-8
# バケット内のファイルの一覧を取得する
import boto
from boto.s3.connection import S3Connection
from boto.s3.key import Key
AWS_KEY_ID = 'aws_key_id'
AWS_SECRET_KEY = 'aws_secret_key'
BUCKET_NAME = 'bucket_name'
conn = S3Connection(AWS_KEY_ID, AWS_SECRET_KEY)
bucket = conn.get_bucket(BUCKET_NAME)
for key in bucket.list():
print key.name, key.size, key.last_modified
# ディレクトリはprefixで指定する
for key in bucket.list(prefix='test/'):
print key.name, key.size, key.last_modified
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment