在boto 2中,您可以使用以下方法写入S3对象:
是否有boto 3等效?将数据保存到存储在S3上的对象的boto3方法是什么?
在boto 3中,'Key.set_contents_from_'方法被替换为
例如:
import boto3
some_binary_data = b'Here we have some data'
more_binary_data = b'Here we have some more data'
# Method 1: Object.put()
s3 = boto3.resource('s3')
object = s3.Object('my_bucket_name', 'my/key/including/filename.txt')
object.put(Body=some_binary_data)
# Method 2: Client.put_object()
client = boto3.client('s3')
client.put_object(Body=more_binary_data, Bucket='my_bucket_name', Key='my/key/including/anotherfilename.txt')
或者,二进制数据可以来自读取文件,如the official docs comparing boto 2 and boto 3中所述:
Storing Data
存储文件,流或字符串中的数据非常简单:
# Boto 2.x from boto.s3.key import Key key = Key('hello.txt') key.set_contents_from_file('/tmp/hello.txt') # Boto 3 s3.Object('mybucket', 'hello.txt').put(Body=open('/tmp/hello.txt', 'rb'))
boto3还有一个直接上传文件的方法:
s3.Bucket('bucketname').upload_file('/local/file/here.txt','folder/sub/path/to/s3key')
http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Bucket.upload_file
这是从s3读取JSON的一个很好的技巧:
import json, boto3
s3 = boto3.resource("s3").Bucket("bucket")
json.load_s3 = lambda f: json.load(s3.Object(key=f).get()["Body"])
json.dump_s3 = lambda obj, f: s3.Object(key=f).put(Body=json.dumps(obj))
现在你可以使用与json.load_s3
和json.dump_s3
相同的API使用load
和dump
data = {"test":0}
json.dump_s3(data, "key") # saves json to s3://bucket/key
data = json.load_s3("key") # read json from s3://bucket/key
在写入S3中的文件之前,您不必再将内容转换为二进制文件。以下示例在带有字符串内容的S3存储桶中创建一个新文本文件(称为newfile.txt):
import boto3
s3 = boto3.resource(
's3',
region_name='us-east-1',
aws_access_key_id=KEY_ID,
aws_secret_access_key=ACCESS_KEY
)
content="String content to write to a new S3 file"
s3.Object('my-bucket-name', 'newfile.txt').put(Body=content)
我用来将文件即时上传到给定的S3存储桶和子文件夹的更简洁的版本 -
import boto3
BUCKET_NAME = 'sample_bucket_name'
PREFIX = 'sub-folder/'
s3 = boto3.resource('s3')
# Creating an empty file called "_DONE" and putting it in the S3 bucket
s3.Object(BUCKET_NAME, PREFIX + '_DONE').put(Body="")
注意:您应该始终将您的AWS凭据(aws_access_key_id
和aws_secret_access_key
)放在单独的文件中,例如-~/.aws/credentials