ChatGPT解决这个技术问题 Extra ChatGPT

如何使用 boto3 将文件或数据写入 S3 对象

在 boto 2 中,您可以使用以下方法写入 S3 对象:

Key.set_contents_from_string()

Key.set_contents_from_file()

Key.set_contents_from_filename()

Key.set_contents_from_stream()

有没有等价的boto 3?将数据保存到存储在 S3 上的对象的 boto3 方法是什么?


C
Community

在 boto 3 中,“Key.set_contents_from_”方法被替换为

对象.put()

Client.put_object()

例如:

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 中所述:

存储数据 从文件、流或字符串中存储数据很简单: # 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'))


botocore.exceptions.NoCredentialsError:无法找到凭据如何解决这个问题?
@deepakmurthy 我不确定您为什么会收到该错误...您需要ask a new Stack Overflow question并提供有关该问题的更多详细信息。
当我尝试 s3.Object().put() 时,我最终得到一个 content-length 为零的对象。对我来说 put() 只接受字符串数据,但 put(str(binarydata)) 似乎有某种编码问题。我最终得到的对象大约是原始数据大小的 3 倍,这对我来说毫无用处。
@user1129682 我不确定为什么会这样。能否请您ask a new question提供更多详细信息?
@jkdev 如果您能take a look,那就太好了。
m
mathetes

boto3还有一个直接上传文件的方法:

s3 = boto3.resource('s3')    
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


这很好,但它不允许存储当前在内存中的数据。
@Reid:对于内存文件,您可以使用 s3.Bucket(...).upload_fileobj() 方法。
从内存中写入与从本地写入的文件上传到 s3 的性能如何?
F
Franke

在写入 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)

不知道我的“放置”操作无权访问。我创建了这个存储桶并将我的规范 ID 放在访问列表下。
在这种情况下,您如何给出 prefix?意思是,如果您想将文件存储在 my-bucket-name/subfolder/ 中怎么办?
@kev 您可以将其与文件名“subfolder/newfile.txt”一起指定,而不是“newfile.txt”
重新“在写入 S3 中的文件之前,您不再需要将内容转换为二进制文件。”,这是否记录在某处?我在看 boto3.amazonaws.com/v1/documentation/api/latest/reference/…,并认为它只接受字节。我不确定究竟是什么构成了“可搜索的类似文件的对象”,但不认为包含字符串。
我可能会将其与用于大型多部分文件上传的 download_fileobj() 进行比较。上传方法需要 seekable file objects,但 put() 允许您将字符串直接写入存储桶中的文件,这对于 lambda 函数动态创建文件并将其写入 S3 存储桶非常方便。
U
Uri Goren

这是一个从 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))

现在您可以通过与 loaddump 相同的 API 使用 json.load_s3json.dump_s3

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

出色的。为了让它工作,我添加了这个额外的位:...["Body"].read().decode('utf-8')
很好的主意。无论如何,它为命名改进提供了一些空间。
k
kev

一个更简洁的版本,我用来将文件即时上传到给定的 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_idaws_secret_access_key)放在单独的文件中,例如 - ~/.aws/credentials


AWS 凭证文件的 Windows 等效位置是什么,因为 Windows 不支持 ~
@HammanSamuel,您可以像 C:\Users\username\.aws\credentials 一样存储它
最好将其存储在 lambda 的环境变量中。
o
ouflak

经过一番研究,我发现了这一点。可以使用简单的 csv 编写器来实现。就是直接把字典写成CSV到S3桶。

eg: data_dict = [{"Key1": "value1", "Key2": "value2"}, {"Key1": "value4", "Key2": "value3"}] 假设所有字典中的键都是制服。

import csv
import boto3

# Sample input dictionary
data_dict = [{"Key1": "value1", "Key2": "value2"}, {"Key1": "value4", "Key2": "value3"}]
data_dict_keys = data_dict[0].keys()

# creating a file buffer
file_buff = StringIO()
# writing csv data to file buffer
writer = csv.DictWriter(file_buff, fieldnames=data_dict_keys)
writer.writeheader()
for data in data_dict:
    writer.writerow(data)
# creating s3 client connection
client = boto3.client('s3')
# placing file to S3, file_buff.getvalue() is the CSV body for the file
client.put_object(Body=file_buff.getvalue(), Bucket='my_bucket_name', Key='my/key/including/anotherfilename.txt')

U
Uri Goren

值得一提的是使用 boto3 作为后端的 smart-open

smart-open 是 python 的 open 的直接替代品,可以从 s3 以及 ftphttp 和许多其他协议打开文件。

例如

from smart_open import open
import json
with open("s3://your_bucket/your_key.json", 'r') as f:
    data = json.load(f)

aws 凭证通过 boto3 credentials 加载,通常是 ~/.aws/ 目录中的文件或环境变量。


虽然此响应提供了丰富的信息,但它并没有坚持回答原始问题 - 即某些 boto 方法的 boto3 等价物是什么。
智能打开使用boto3
@UriGoren 你能分享一个使用智能打开的 ftp 到 s3 的例子吗?
P
Prateek Bhuwania

您可以使用以下代码编写,例如 2019 年的 S3 映像。为了能够连接到 S3,您必须使用命令 pip install awscli 安装 AWS CLI,然后使用命令 aws configure 输入一些凭证:

import urllib3
import uuid
from pathlib import Path
from io import BytesIO
from errors import custom_exceptions as cex

BUCKET_NAME = "xxx.yyy.zzz"
POSTERS_BASE_PATH = "assets/wallcontent"
CLOUDFRONT_BASE_URL = "https://xxx.cloudfront.net/"


class S3(object):
    def __init__(self):
        self.client = boto3.client('s3')
        self.bucket_name = BUCKET_NAME
        self.posters_base_path = POSTERS_BASE_PATH

    def __download_image(self, url):
        manager = urllib3.PoolManager()
        try:
            res = manager.request('GET', url)
        except Exception:
            print("Could not download the image from URL: ", url)
            raise cex.ImageDownloadFailed
        return BytesIO(res.data)  # any file-like object that implements read()

    def upload_image(self, url):
        try:
            image_file = self.__download_image(url)
        except cex.ImageDownloadFailed:
            raise cex.ImageUploadFailed

        extension = Path(url).suffix
        id = uuid.uuid1().hex + extension
        final_path = self.posters_base_path + "/" + id
        try:
            self.client.upload_fileobj(image_file,
                                       self.bucket_name,
                                       final_path
                                       )
        except Exception:
            print("Image Upload Error for URL: ", url)
            raise cex.ImageUploadFailed

        return CLOUDFRONT_BASE_URL + id